当应用程序处于非活动状态时,如何创建Forground服务永远不会停止 [英] How to Create Forground Service Never Stop when Application is Inactive

查看:237
本文介绍了当应用程序处于非活动状态时,如何创建Forground服务永远不会停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个要在其中启动服务的应用程序第一次打开该应用程序.当该应用程序处于前台状态时每5或10分钟收到本地通知.但是仅在应用程序活动或最近使用的应用程序时才收到通知. app通知未收到.我希望此服务在设备上继续运行.

I have created one application in which I want to start service First time open the application.when application is in foreground Every 5 or 10 minutes Local Notification received.but Notification received only When Application Active or Recent app.When Clear the Recent app Notification Does't receive.I wanted this service to keep running on the device.

创建的服务和启动服务的示例代码: 启动服务:

Sample code of created service and start services: Start the service:

    Intent i=new Intent(MainActivity.this,MyService.class);       
    startService(i);

服务:

    public class MyService extends Service {
    final static String TAG = MyService.class.getName();
    ReceiverCall receiverCall;


    private static final int NOTIFICATION_ID = 1;

    MyService (){
        super();
        }
    class Mythread implements Runnable {
        int service_id;

        Mythread(int service_id) {
            this.service_id = service_id;
        }

        @Override
        public void run() {
            int i = 0;
            synchronized (this) {
               // while (i < 10) {
                    try {
                        wait(2500);
                        i++;
                        processStartNotification(String.valueOf(i));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
               // }
            }
        }
    }

    @Override
    public void onCreate() {
         receiverCall= new ReceiverCall();
            super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        super.onDestroy();
        Toast.makeText(getApplicationContext(), "Service Task destroyed", Toast.LENGTH_LONG).show();


        Intent myIntent = new Intent(getApplicationContext(), MyService.class);
        startService(myIntent);



    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Intent myIntent = new Intent(getApplicationContext(), MyService.class);
        startService(myIntent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

      Thread thread = new Thread(new Mythread(startId));
        thread.start();

        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private void processStartNotification(String s) {
        // Do something. For example, fetch fresh data from backend to create a rich notification?

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle("Scheduled Notification")
                .setAutoCancel(true)
                .setColor(getResources().getColor(R.color.colorAccent))
                .setContentText(" Notification Service"+s)
                .setSmallIcon(R.drawable.ic_launcher_background);
        builder.setDeleteIntent(receiverCall.getDeleteIntent(this));
        final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, builder.build());

    }
    }

BroadcastReceiver Class :

    public class ReceiverCall extends BroadcastReceiver {
    private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
    private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
    private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Service Stops", "Ohhhhhhh");
        context.startService(new Intent(context, MyService.class));
    }
    public static PendingIntent getDeleteIntent(Context context) {
        Intent intent = new Intent(context, ReceiverCall.class);
        intent.setAction(ACTION_DELETE_NOTIFICATION);
        return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
    }   

清单声明:

      <service
            android:name=".MyService"
            android:exported="true"
            android:stopWithTask="false"></service>

         <receiver android:name=".ReceiverCall">
            <intent-filter>
                <action android:name="com.servicesex" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

是否可以始终在应用程序暂停或其他任何时间运行该服务.一段时间后,我的应用程序暂停,服务也暂停或停止.因此,我如何在后台始终运行此服务.

Is it possible to run this service always as when the application pauses and anything else. After some time my application goes pause and the services also go pause or stop. So how can I run this service in background and always.

推荐答案

public class MyService extends Service {
static final int NOTIFICATION_ID = 100;

public static boolean isServiceRunning = false;

@Override
public void onCreate() {
    super.onCreate();
    startServiceWithNotification();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getAction().equals(C.ACTION_START_SERVICE)) {
        startServiceWithNotification();
    }
    else stopMyService();
    return START_STICKY;
}

// In case the service is deleted or crashes some how
@Override
public void onDestroy() {
    isServiceRunning = false;
    super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
    // Used only in case of bound services.
    return null;
}


void startServiceWithNotification() {
    if (isServiceRunning) return;
    isServiceRunning = true;

    Intent notificationIntent = new Intent(getApplicationContext(), MyActivity.class);
    notificationIntent.setAction(C.ACTION_MAIN);  // A string containing the action name
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent contentPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.my_icon);

    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setTicker(getResources().getString(R.string.app_name))
            .setContentText(getResources().getString(R.string.my_string))
            .setSmallIcon(R.drawable.my_icon)
            .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
            .setContentIntent(contentPendingIntent)
            .setOngoing(true)
//                .setDeleteIntent(contentPendingIntent)  // if needed
            .build();
    notification.flags = notification.flags | Notification.FLAG_NO_CLEAR;     // NO_CLEAR makes the notification stay when the user performs a "delete all" command
    startForeground(NOTIFICATION_ID, notification);
}

void stopMyService() {
    stopForeground(true);
    stopSelf();
    isServiceRunning = false;
}
}

C =是必须以程序包名称开头的字符串

C = are the Strings that must start with the package name

这篇关于当应用程序处于非活动状态时,如何创建Forground服务永远不会停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆