Android 後台每10秒鐘啟動一次應用的demo,一次啟動,永不退出

來源:互聯網
上載者:User

標籤:cti   current   demo   null   rod   graphics   end   應用   run   

android整理

原文連結

建立一個Service:

最關鍵的是onStartCommand 裡面返回的Service.START_STICKY, 

package com.qywanwei.servicetest2;import android.app.Notification;import android.app.PendingIntent;import android.app.Service;import android.content.Intent;import android.graphics.BitmapFactory;import android.os.IBinder;import android.support.v7.app.NotificationCompat;import android.util.Log;import android.content.ComponentName;import android.content.Context;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.content.pm.ResolveInfo;import java.util.List;public class MyService extends Service  implements  Runnable{    private Thread thread;    public MyService() {    }    @Override    public IBinder onBind(Intent intent) {        // TODO: Return the communication channel to the service.        throw new UnsupportedOperationException("Not yet implemented");    }    //建立服務時候調用,第一次建立    @Override    public void onCreate() {        super.onCreate();        Log.d("MyServer", "onCreate: 建立服務");        //onCreate的時候建立初始化        thread = new Thread( this);        thread.start();//        前台服務//        Intent intent=new Intent(this,MainActivity.class);//        PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,0);//        Notification notification=new NotificationCompat.Builder(this)//                .setContentTitle("111")//                .setContentText("22")//                .setWhen(System.currentTimeMillis())//                .setSmallIcon(R.mipmap.ic_launcher)//                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))//                .setContentIntent(pendingIntent)//                .build();//        startForeground(1,notification);    }    //每次服務啟動調用,每次啟動    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.d("MyServer", "onCreate: 啟動服務");        //如果服務並停止了,重建一個新的        if(thread.isInterrupted()){            thread = new Thread(this);            thread.start();        }        return Service.START_STICKY;//        return super.onStartCommand(intent, flags, startId);    }    @Override    public void run() {        int i=0;        while (true){            try {                //每10秒鐘進行一次輸出                Thread.sleep(10000);                //Toast.makeText(getApplicationContext(),"服務啟動"+i++,Toast.LENGTH_LONG).show();                Log.d("MyServer", "服務啟動"+i++);                openApp("com.qywanwei.servicetest2");            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    //    private void openApp(View v, String packageName) {    private void openApp(String packageName) {        //Context context = v.getContext();        PackageInfo pi = null;        //PackageManager pm = context.getPackageManager();        PackageManager pm = getPackageManager();        try {            pi = pm.getPackageInfo(packageName, 0);        } catch (PackageManager.NameNotFoundException e) {            e.printStackTrace();        }        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);        resolveIntent.setPackage(pi.packageName);        List<ResolveInfo> apps = pm.queryIntentActivities(resolveIntent, 0);        ResolveInfo ri = apps.iterator().next();        if (ri != null ) {            packageName = ri.activityInfo.packageName;            String className = ri.activityInfo.name;            Intent intent = new Intent(Intent.ACTION_MAIN);            intent.addCategory(Intent.CATEGORY_LAUNCHER);            ComponentName cn = new ComponentName(packageName, className);            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);            intent.setComponent(cn);            startActivity(intent);        }    }    //服務銷毀的時候    @Override    public void onDestroy() {        super.onDestroy();        Log.d("MyServer", "onCreate: 銷毀服務");    }}

  

Android 後台每10秒鐘啟動一次應用的demo,一次啟動,永不退出

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.