How to get android notifications when app was closed?

£可爱£侵袭症+ 提交于 2019-11-27 18:52:58

Add a (started) Service to your application. Even though the user quitted your app, the service will still run in the background.

Furthermore you can implement a BroadcastReceiver that will listen to the phone's Intents and let your service be started when the phone boots !

MyService.java

public class MyService extends Service {

@Override
public int onStartCommand(Intent intent, int flags, int startId){
    // START YOUR TASKS
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
    // STOP YOUR TASKS
super.onDestroy();
}

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

BootReceiver.java

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            Intent serviceIntent = new Intent("your.package.MyService");
            context.startService(serviceIntent);
            }
        }
    }
}

AndroidManifest.xml

// in manifest tag

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

// in your application tag

<service android:name=".MyService">
    <intent-filter>
        <action android:name="your.package.MyService" />
    </intent-filter>
</service>

<receiver
    android:name=".BootReceiver"
    android:enabled="true"
    android:exported="true"
    android:label="BootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

If you want to start your service from an activity, just use

private boolean isMyServiceRunning() {
         ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
         for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
             if (MyService.class.getName().equals(service.service.getClassName())) {
                 return true;
             }
         }
         return false;
     }

if (!isMyServiceRunning()){
     Intent serviceIntent = new Intent("your.package.MyService");
     context.startService(serviceIntent);
}

If data comes from your server then utilizing GCM might be good approach. In this case server will have ability to wake/start your application.

Creating a service which is constantly running in your case is a crappy solution. IMO better approach is use of AlarmManager. Alarm manager will invoke intent on specific time. (note that if phone reboots you have to register intent again).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!