如果应用程序在android中的后台如何发送通知?

时间:2014-05-23 01:19:20

标签: android service notifications android-activity android-lifecycle

目前我正在进行蓝牙扫描,这意味着我将继续扫描设备,如果附近有设备,我会在屏幕上显示,但是,如果应用程序在后台,我需要向用户。

现在我的工作逻辑是这样的,有一个主类可以激活扫描服务,扫描服务工作是返回扫描设备列表。主要的工作是显示/处理结果。

代码是这样的:

服务

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);
    }
}

主要

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);
                }
            }

        }
    }
}

问题是,如果我需要添加通知,是否需要将流程部分代码(在主类中)移动到服务?我怎样才能实现它?谢谢

2 个答案:

答案 0 :(得分:1)

您可以显示来自任何主要或服务类的通知。如果要显示Main的通知,请在onReceive(Context context,Intent intent)方法中使用COntext( context.getSystemService()

试试这段代码:

    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);

答案 1 :(得分:1)

首先,您需要检查您的应用程序是否在后台。 您可以在应用中的每项活动onPause()上调用以下代码:

/**
* 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;
}

在清单文件中添加以下行:

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

要添加通知,您可以添加以下代码:

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);

 }