How to send notification if the app is at the back

2019-08-28 08:38发布

Currently I am working on bluetooth scan, that means I will keep scanning the device, if there is device nearby , I will show it on screen, however, if the app is at the background, I need to show notification to the user.

And now my working logic is like this, there is a main class that fire the scan service, the scan service job is to return a list of scanned device. And the main class job is to display/ process the result.

The code is like this:

Service

public class Detector extends Service implements IBeaconConsumer {

    protected static final String TAG = "RangingActivity";
    private IBeaconManager iBeaconManager;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        iBeaconManager = IBeaconManager.getInstanceForApplication(this);
        iBeaconManager.bind(this);
        Log.d("test1","bind");
        return super.onStartCommand(intent, flags, startId);
    }
}

Main

private class DataUpdateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("scanResult")) {
            ArrayList<IBeacon> beacons = (ArrayList<IBeacon>) intent.getSerializableExtra("beacons");

            for(IBeacon be : beacons){
                if (be.getProximityUuid().equals("ebefd083-70a2-47c8-9837-e7b5634df524")) {
                    if (be.getMajor() == 2) {
                        a_rssi = be.getRssi();
                    } else if (be.getMajor() == 1) {
                        b_rssi = be.getRssi();
                    }
                }
            }

            if(a_rssi > b_rssi) {
                Log.d("test1","at shop");
                //at shop,need case handling if more than 1 shop beacon
                showAd(R.drawable.offer1);

                if (timer != null)
                    timer.cancel();

                timer = null;
                timeCount = 0;

                Intent msg = new Intent("timerUpdate");
                msg.putExtra("timeCount", timeCount);
                sendBroadcast(msg);
            } else {
                Log.d("test1","at park");

                //at car park
                if (timer == null) {
                    timer = new Timer(true);
                    timer.schedule(new MyTimer(), 1000, 1000);
                }
            }

        }
    }
}

The problem is , if I need to add notification, does I need to move the process part code (which is in the main class) to service? How can I achieve it? Thanks

2条回答
Anthone
2楼-- · 2019-08-28 08:47

You can show notification from any of your Main or Service class. If you want to show notification from Main then use COntext in onReceive(Context context, Intent intent) method (context.getSystemService())

Try this code snippet :

    NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(R.drawable.ic_launcher,
            "Hello from service", System.currentTimeMillis());
    Intent intent = new Intent(this, MainActivity.class);
    notification.setLatestEventInfo(this, "contentTitle", "contentText",
    PendingIntent.getActivity(this, 1, intent, 0));
    manager.notify(123, notification);
查看更多
神经病院院长
3楼-- · 2019-08-28 09:04

First you need to check if your application is in background. You can call below code on onPause() on every activity in your application:

/**
* Checks if the application is being sent in the background (i.e behind
* another application's Activity).
* 
* @param context the context
* @return <code>true</code> if another application will be above this one.
*/
public static boolean isApplicationSentToBackground(final Context context) {
 ActivityManager am = (ActivityManager)    context.getSystemService(Context.ACTIVITY_SERVICE);
 List<RunningTaskInfo> tasks = am.getRunningTasks(1);
 if (!tasks.isEmpty()) {
  ComponentName topActivity = tasks.get(0).topActivity;
  if (!topActivity.getPackageName().equals(context.getPackageName())) {
    return true;
  }
 }

 return false;
}

Add this line in your manifest file :

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

For adding notification you can add this code :

private void addNotification(Context context, String message) {

 int icon = R.drawable.ic_launcher;
 long when = System.currentTimeMillis();
 String appname = context.getResources().getString(R.string.app_name);
 NotificationManager notificationManager = (NotificationManager) context
 .getSystemService(Context.NOTIFICATION_SERVICE);

 Notification notification;
 PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
 new Intent(context, myactivity.class), 0);


 NotificationCompat.Builder builder = new NotificationCompat.Builder(
 context);
 notification = builder.setContentIntent(contentIntent)
 .setSmallIcon(icon).setTicker(appname).setWhen(0)
 .setAutoCancel(true).setContentTitle(appname)
 .setContentText(message).build();

 notificationManager.notify(0 , notification);

 }
查看更多
登录 后发表回答