前台服务,让服务可见

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>




阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭