应用为后台时发送通知

时间:2014-11-19 13:09:35

标签: android

我的应用在后台时发送通知。当应用程序是后台时发送通知但是当我单击通知并打开应用程序时,应用程序崩溃。当应用程序仅在后台时我需要发送通知,而我一直在为iBeacon开发这样做。

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
         notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            ;


           new ForegroundCheckTask().execute();

    }


    class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {

          @Override
          protected Boolean doInBackground(Context... params) {

              postNotificationUBCity("Entered region");
            final Context context = params[0].getApplicationContext();

            return isAppOnForeground(context);


          }

          private boolean isAppOnForeground(Context context) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
            if (appProcesses == null) {
              return false;
            }
            final String packageName = context.getPackageName();
            for (RunningAppProcessInfo appProcess : appProcesses) {
              if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
                return true;
              }
            }
            return false;
          }
        }

记录:

11-19 18:31:01.300: E/AndroidRuntime(13008): java.lang.RuntimeException: An error occured while executing doInBackground()
11-19 18:31:01.300: E/AndroidRuntime(13008):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-19 18:31:01.300: E/AndroidRuntime(13008):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-19 18:31:01.300: E/AndroidRuntime(13008):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-19 18:31:01.300: E/AndroidRuntime(13008):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-19 18:31:01.300: E/AndroidRuntime(13008):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-19 18:31:01.300: E/AndroidRuntime(13008):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-19 18:31:01.300: E/AndroidRuntime(13008):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-19 18:31:01.300: E/AndroidRuntime(13008):    at java.lang.Thread.run(Thread.java:841)
11-19 18:31:01.300: E/AndroidRuntime(13008): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
11-19 18:31:01.300: E/AndroidRuntime(13008):    at com.example.beacon.MainActivity$ForegroundCheckTask.doInBackground(MainActivity.java:450)
11-19 18:31:01.300: E/AndroidRuntime(13008):    at com.example.beacon.MainActivity$ForegroundCheckTask.doInBackground(MainActivity.java:1)
11-19 18:31:01.300: E/AndroidRuntime(13008):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-19 18:31:01.300: E/AndroidRuntime(13008):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-19 18:31:01.300: E/AndroidRuntime(13008):    ... 4 more

1 个答案:

答案 0 :(得分:0)

我不会为此目的使用AsyncTask。

如果您想在应用程序处于后台模式时发送通知,请尝试在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;
}

添加适当的通知:

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

 }

请勿忘记在AndroidManifest上添加权限:

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

这应该有效。