zoukankan      html  css  js  c++  java
  • Android Service 不被杀死并提高优先级

    Android Service 不被杀死有两种思路,一种是将APP设置为系统应用。还有一种是增强service的生命力。即使屏幕背光关闭时也能执行。

    因为设置为系统应用须要root。所以一般使用后一种方法:

    1.Androidmanifest.xml权限许可:-----------------------------------------------------------------
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <service android:name="com.xx.MyService" ></service>

    2.主Activity:----------------------------------------------------------------------------------------

    private ServiceConnection conn=null;
    private PowerManager.WakeLock mwl;

    @Override
    protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mian);
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mwl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyTag");
    mwl.acquire();//屏幕关闭后保持活动


    Intent service=new Intent(this,MyService.class);
    startService(service);
    conn = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName name) { }
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) { //……}
    };
    bindService(service, conn, BIND_AUTO_CREATE);
    //绑定服务
    }

    @Override
    protected void onDestroy() {
    //mwl.release();//释放
    unbindService(conn);//解绑
    super.onDestroy();
    }

    ------------------------------------------------------------------------------------------------------

    Android Service 提高优先级:

    public class MyService extendsService{
    @Override
    public IBinder onBind(Intent intent) {
    Notification notification = new Notification(R.drawable.ic_launcher, "title",System.currentTimeMillis());
            PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
            notification.setLatestEventInfo(this, "Service",  "service is running", pintent);
            startForeground(0, notification);//设置最高级进程。 id 为 0状态栏的 notification 将不会显示
    return new MyBinder();
    }
    class MyBinder extendsBinder{ //……  }
    @Override
    public void onDestroy() {
    stopForeground(true);//取消最高级进程
    super.onDestroy();
    }
    }


  • 相关阅读:
    MAC OSX 进程间通信
    UVa 10397 Connect the Campus
    ios 类似的效果淘宝商品详细页面
    Programming from the ground up(0)
    解决因特网和xshell考虑到问题
    除去在阵列中重复元件
    Cocos2d-x 手机游戏《疯狂的蝌蚪》资源 “开源” win32+安德鲁斯+iOS三合一
    (四)左右ng-app自己主动bootstrap相框
    Codeforces 338D GCD Table 中国剩余定理
    十月金在线编程竞赛的第二个冠军:解密
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/6957036.html
Copyright © 2011-2022 走看看