代码之家  ›  专栏  ›  技术社区  ›  Nikhil

如何像WhatsApp那样在后台运行服务,以便在没有唤醒设备的情况下备份聊天记录?

  •  0
  • Nikhil  · 技术社区  · 5 年前

    在我的应用程序中,我需要在每天午夜做一些任务。我使用AlarmManager和服务实现了这一点,但当我的任务启动时,它会唤醒设备并启动应用程序。我怎么能像背景里的WhatsApp那样呢?

    0 回复  |  直到 5 年前
        1
  •  1
  •   Istiak    5 年前

    service 用过了。

    extend Service

    public class service extends Service {
    
    // declaring object of MediaPlayer
    private MediaPlayer player;
    
    public service() {
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        onTaskRemoved(intent);
        Toast.makeText(getApplicationContext(),"This is a Service running in Background",
                Toast.LENGTH_SHORT).show();
        player = MediaPlayer.create(getApplicationContext(),R.raw.ringtone);
        player.start();
        startForegroundService(intent);
        return START_STICKY;
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());
        restartServiceIntent.setPackage(getPackageName());
        startService(restartServiceIntent);
        super.onTaskRemoved(rootIntent);
    }
    @Override
    public ComponentName startForegroundService(final Intent service) {
        return startForegroundService(service);
    }
    }
    

    运行您编写的源代码

    Intent intent = new Intent(this, service.class);
    ContextCompat.startForegroundService(this,intent);
    

    或者,您可以使用

    startService(new Intent(getApplicationContext(),service.class));
    

    这是你的答案 git repo

        2
  •  0
  •   KotlinIsland    5 年前

    你可以用WorkManager,这是最好的方法。 我用它做背景处理,效果很不错。 https://developer.android.com/topic/libraries/architecture/workmanager