我如何让我的应用程序运行,即使应用程序被杀死?当它从最近的应用程序中删除时,它就被杀死了

koaltpgm  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(352)

我正在开发一个应用程序,可以计算一整天解锁的次数。
我见过许多类似的问题,但没有一个有效!!任何人可以帮助我,请提供上述问题的代码片段。
甚至要确保你提供的解决方案适用于androido及更高版本
主活动.java

public class MainActivity extends AppCompatActivity {
MyReceiver myReceiver;
IntentFilter filter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myReceiver = new MyReceiver();
    filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
    registerReceiver(myReceiver, filter);
}}

我的接收器.java

public class MyReceiver extends BroadcastReceiver {
   private static final String TAG = "BroadCast Receiver";
   @Override
   public void onReceive(Context context, Intent intent) {
       if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
          Toast.makeText(context, "DEVICE_IS_UNLOCKED",Toast.LENGTH_LONG).show();
          Log.i(TAG, "Unlocked");
       }
   }
}
yzxexxkh

yzxexxkh1#

在前台启动服务https://androidwave.com/foreground-service-android-example/?

jgovgodb

jgovgodb2#

你需要做后台服务。
试试下面的代码。

public class BackgroundUpdateService extends Service {

    /**
     * Author:Hardik Talaviya
     * Date:  2019.08.3 2:30 PM
     * Describe:
     */

    private static final String TAG = "BackgroundLocation";
    private Context context;
    private boolean stopService = false;
    private Handler handler;
    private Runnable runnable;
    private NotificationCompat.Builder builder = null;
    private NotificationManager notificationManager;

    @Override
    public void onCreate() {
        Log.e(TAG, "Background Service onCreate :: ");
        super.onCreate();
        context = this;

        handler = new Handler();
        runnable = new Runnable() {

            @Override
            public void run() {
                try {
                    //Add Here your code if you want start in background
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    handler.postDelayed(this, TimeUnit.SECONDS.toMillis(2));
                }
            }
        };
        if (!stopService) {
            handler.postDelayed(runnable, TimeUnit.SECONDS.toMillis(2));
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Log.e(TAG, "onTaskRemoved :: ");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand :: ");
        StartForeground();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "BackgroundService onDestroy :: ");
        stopService = true;
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
    }

    /*-------- For notification ----------*/
    private void StartForeground() {
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

        String CHANNEL_ID = "channel_location";
        String CHANNEL_NAME = "channel_location";

        notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            notificationManager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
            builder.setColorized(false);
            builder.setChannelId(CHANNEL_ID);
            builder.setColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
            builder.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE);
        } else {
            builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
        }
        builder.setOnlyAlertOnce(true);
        builder.setContentTitle(context.getResources().getString(R.string.app_name));
        builder.setContentText("Your Text");
        Uri notificationSound = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
        builder.setSound(notificationSound);
        builder.setAutoCancel(true);
        builder.setSmallIcon(R.mipmap.ic_notification_app_icon);
        builder.setContentIntent(pendingIntent);
        startForeground(101, builder.build());
    }
}

在您的清单中添加此行

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<service
    android:name=".BackgroundUpdateService"
    android:enabled="true" />

并使用下面的代码从您的活动中启动和停止服务

Intent someIntent = new Intent(MainActivity.this, BackgroundUpdateService.class);
startService(someIntent);//For start service
stopService(someIntent); //For stop service

我希望这能帮助你!
谢谢您。

相关问题