前台服务,让服务可见

public class MyService extends Service {//需要在manifest文件中注册
    //自身调用stopself()也可以停止服务运行

    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("mydate" , "oncreate");

        //在oncreate()方法中加入Notification通知
        //并调用startForeground(),即可将srvice变成前台服务,并显示出来,并且点击有pendingintent
        Intent intent = new Intent(this , MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this , 0 , intent , 0);
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("这是前台服务的标题")
                .setContentText("这是前台服务的内容")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources() , R.mipmap.ic_launcher))
                .setContentIntent(pendingIntent) //将点击的intent传入
                .build();
        startForeground(1 , notification); //开启前台服务

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("mydate" , "onstartcommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.i("mydate" , "ondestroy");
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        /*// TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");*/

        return (new MyBinder()); //具体干嘛,做什么 ,如果没有指定干嘛的话就为空
    }

    class MyBinder extends Binder { //活动指挥服务干嘛,做什么什么,需要这个东西决定具体做什么
        public void startDownload(){
            Log.i("mydate" , "开始下载");
        }
        //...
    }


}
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(MainActivity.this , MyService.class);
        startService(intent); //启动服务

    }
}
<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name="layout.MyService"
            android:enabled="true"
            android:exported="true"></service>
    </application>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值