Android 如何在应用程序处于非活动状态时创建Forground Service永不停止
我已创建了一个应用程序,我想在其中首次启动服务打开该应用程序。当应用程序位于前台时,每5或10分钟收到一次本地通知。但仅当应用程序处于活动状态或最近的应用程序时才收到通知。清除时,最近的应用程序通知不会收到。我希望此服务继续运行这个装置 已创建服务和启动服务的示例代码: 启动服务:Android 如何在应用程序处于非活动状态时创建Forground Service永不停止,android,google-maps,android-fragmentactivity,Android,Google Maps,Android Fragmentactivity,我已创建了一个应用程序,我想在其中首次启动服务打开该应用程序。当应用程序位于前台时,每5或10分钟收到一次本地通知。但仅当应用程序处于活动状态或最近的应用程序时才收到通知。清除时,最近的应用程序通知不会收到。我希望此服务继续运行这个装置 已创建服务和启动服务的示例代码: 启动服务: Intent i=new Intent(MainActivity.this,MyService.class); startService(i); 服务: public clas
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);
}
}
公共类MyService扩展服务{
最后一个静态字符串标记=MyService.class.getName();
接管人电话;
私有静态最终整数通知_ID=1;
我的服务(){
超级();
}
类Mythread实现可运行{
内部服务标识;
Mythread(内部服务\u id){
this.service\u id=service\u id;
}
@凌驾
公开募捐{
int i=0;
已同步(此){
//而(i<10){
试一试{
等待(2500);
i++;
processStartNotification(String.valueOf(i));
}捕捉(中断异常e){
e、 printStackTrace();
}
// }
}
}
}
@凌驾
public void onCreate(){
receiverCall=新的receiverCall();
super.onCreate();
}
@凌驾
公共空间{
super.ondestory();
super.ondestory();
Toast.makeText(getApplicationContext(),“服务任务已销毁”,Toast.LENGTH_LONG.show();
Intent myIntent=newintent(getApplicationContext(),MyService.class);
startService(myIntent);
}
@凌驾
公共void onTaskRemoved(Intent rootIntent){
super.onTaskRemoved(rootIntent);
Intent myIntent=newintent(getApplicationContext(),MyService.class);
startService(myIntent);
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
线程线程=新线程(新的Mythread(startId));
thread.start();
返回开始时间;
}
@可空
@凌驾
公共IBinder onBind(意向){
返回null;
}
私有void processStartNotification(字符串s){
//做一些事情。例如,从后端获取新数据以创建富通知?
最终NotificationCompat.Builder=新NotificationCompat.Builder(本);
builder.setContentTitle(“计划通知”)
.setAutoCancel(真)
.setColor(getResources().getColor(R.color.colorAccent))
.setContentText(“通知服务”+s)
.setSmallIcon(R.drawable.ic_启动器_背景);
builder.setDeleteIntent(receiverCall.getDeleteIntent(this));
final NotificationManager manager=(NotificationManager)this.getSystemService(Context.NOTIFICATION_服务);
manager.notify(NOTIFICATION_ID,builder.build());
}
}
广播接收器类别:
公共类ReceiverCall扩展了BroadcastReceiver{
私有静态最终字符串ACTION\u START\u NOTIFICATION\u SERVICE=“ACTION\u START\u NOTIFICATION\u SERVICE”;
私有静态最终字符串ACTION\u DELETE\u NOTIFICATION=“ACTION\u DELETE\u NOTIFICATION”;
专用静态最终整数通知时间间隔(单位:小时)=2;
@凌驾
公共void onReceive(上下文、意图){
Log.i(“服务站”、“Ohhhhhhhhh”);
startService(新意图(context,MyService.class));
}
公共静态PendingEvent getDeleteIntent(上下文){
意向意向=新意向(上下文,ReceiverCall.class);
意图.设置动作(动作\删除\通知);
返回PendingEvent.getBroadcast(上下文,0,意图,PendingEvent.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>
是否可以像应用程序暂停或其他任何操作一样始终运行此服务。一段时间后,我的应用程序会暂停,服务也会暂停或停止。因此,我如何在后台始终运行此服务
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=是必须以包名开头的字符串您可以使用报警管理器在特定时间安排未来任务,并在触发时重新设置。或者新的api,它可以帮助运行任务,甚至应用程序被杀死
但我认为,当你的应用程序从系统任务中删除时,保持服务运行是一种不好的做法,因为该服务一直在消耗内存和电源。最好遵循这个Intent startinent=newintent(getApplicationContext(),MyService.class);启动。设置操作(C.操作\启动\服务);startService(Startinent);这些字符串必须以包名开头。public static final String ACTION\u start\u SERVICE=“com.example.rakesh.demo.MainActivity”;应用程序关闭或终止时未收到通知