下载解析通知时,Android App挂起

时间:2015-08-07 14:18:27

标签: android parse-platform push-notification

我的Android应用程序在下载解析通知时挂起,图像在使用应用时准确无误。现在我知道可以启动一项服务,但我想避免这样做。我应该怎么做,以便我的应用程序不会挂起。

ParseReceiver.java

  public class ParseReceiver extends ParsePushBroadcastReceiver{

Bundle AnalyticsBundle;
String title = "";
String message = "";
String action_id = "";
String action_type = "";
String imageUrl = "";
String notType = "";
TripHomePage tripPageHome;

@Override
public void onPushReceive(final Context context, Intent intent) {
    AnalyticsBundle=intent.getExtras();



    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    try {


        JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));

        try {
            if (json.has("aps")) {
                json = json.getJSONObject("aps");
            }
        } catch (Exception e) {
        }


        if (json.has("title")) {
            title = json.getString("title").toString();
        }
        if (json.has("message")) {
            message = json.getString("message").toString();
        }

        if (json.has("action_type")) {
            action_type = json.getString("action_type").toString();

        }
        if (json.has("action_id")) {
            action_id = json.getString("action_id").toString();

        }
        if (json.has("url_image")) {

            imageUrl = json.getString("url_image").toString();

        }

        if (json.has("notification_type")) {
            notType = json.getString("notification_type").toString();
        }

        Boolean check=pref2.getBoolean("keyfornotification",true);
        if(check==true)
        {
            generateNotification(notType, title, message, action_id, action_type, imageUrl, context);

        }
        else if(check==false)
        {
            if(action_type.equals("UpdateApp"))
            {
                generateNotification(notType, title, message, action_id, action_type, imageUrl, context);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }


}

public void generateNotification(String notType,String title, String message, String action_id, String action_type,String imageUrl,Context context){

    try {

            if (notType.equals("normalt") || notType.equalsIgnoreCase("NormalText")) {
                showtext(title, message, action_type, action_id, context);
            }
            if (notType.equals("bigi") || notType.equalsIgnoreCase("Bigimage")) {
                bigPicture(title, message, imageUrl, action_type, action_id, context);
            }
            if (notType.equals("overlay") || notType.equalsIgnoreCase("Overlay")) {
                bigOverlay(title, message, imageUrl, action_type, action_id, context);
            }


    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }




}

public void showtext(String title, String message, String actionType, String actionId, Context context) {

    Bitmap tripotoLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.med);

    PendingIntent contentIntent = PendingIntent.getActivities(context,
            (int) (Math.random() * 100), getIntent(actionType, actionId, context),
            PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notif;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        notif = new NotificationCompat.Builder(context)
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(R.drawable.tripotoblack).setColor(Color.BLACK)
                .setLargeIcon(tripotoLogo).setContentIntent(contentIntent)
                .setStyle(new NotificationCompat.BigTextStyle()
                .bigText(message))
                .build();
    } else {


        notif = new NotificationCompat.Builder(context)
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(R.drawable.smalli)
                .setLargeIcon(tripotoLogo).setContentIntent(contentIntent)
                .setStyle(new NotificationCompat.BigTextStyle()
                .bigText(message))
                .build();
    }


    notif.flags |= Notification.FLAG_AUTO_CANCEL;

    // Play default notification sound
    notif.defaults |= Notification.DEFAULT_SOUND;
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, notif);


}

public void bigPicture(String title, String message, String url, String actionType, String actionId, Context context) {

    Bitmap tripImage = null;
    InputStream in = null;
    try {
        in = new URL(url).openStream();
        tripImage = BitmapFactory.decodeStream(in);

    } catch (IOException e) {
        e.printStackTrace();
    }
    Bitmap largeicon = BitmapFactory.decodeResource(context.getResources(), R.drawable.smalli);

    PendingIntent contentIntent = PendingIntent.getActivities(context,
            (int) (Math.random() * 100), getIntent(actionType, actionId, context),
            PendingIntent.FLAG_UPDATE_CURRENT);


    Notification n;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        n = new NotificationCompat.Builder(context)
                .setContentTitle(title)
                .setContentText(message).setContentIntent(contentIntent)
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(tripImage).setBigContentTitle(title).setSummaryText(message)).setTicker(title).setSmallIcon(R.drawable.tripotoblack).setColor(Color.BLACK)
                .setLargeIcon(largeicon)
                .build();
    } else {


        n = new NotificationCompat.Builder(context)
                .setContentTitle(title)
                .setContentText(message).setContentIntent(contentIntent)
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(tripImage).setBigContentTitle(title).setSummaryText(message)).setTicker(title).setSmallIcon(R.drawable.smalli)
                .setLargeIcon(largeicon)
                .build();


    }
    n.flags |= Notification.FLAG_AUTO_CANCEL;

    // Play default notification sound
    n.defaults |= Notification.DEFAULT_SOUND;
    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, n);


}


public void bigOverlay(String title, String message, String url, String actionType, String actionId, Context context) {


    Bitmap tripImage = null;
    InputStream in = null;
    try {
        in = new URL(url).openStream();
        tripImage = BitmapFactory.decodeStream(in);

    } catch (IOException e) {
        e.printStackTrace();
    }
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);


    RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.bigo);
    contentView.setImageViewBitmap(R.id.imageView, tripImage);
    contentView.setTextViewText(R.id.textView, title);
    contentView.setTextViewText(R.id.textView2, message);

    Bitmap largei = BitmapFactory.decodeResource(context.getResources(), R.drawable.med);


    PendingIntent contentIntent = PendingIntent.getActivities(context,
            (int) (Math.random() * 100), getIntent(actionType, actionId, context),
            PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        notification = new NotificationCompat.Builder(context).setContentInfo("Tripoto:")
                .setSmallIcon(R.drawable.tripotoblack).setContentText(message).setContentTitle(title).setColor(Color.BLACK)
                .setTicker(title).setLargeIcon(largei).setContentIntent(contentIntent)
                .setContentIntent(contentIntent).setPriority(2).setStyle(new NotificationCompat.BigPictureStyle()
                        .setBigContentTitle(title).setSummaryText(message))
                .build();
    } else {

        notification = new NotificationCompat.Builder(context).setContentInfo("Tripoto:")
                .setSmallIcon(R.drawable.smalli).setContentText(message).setContentTitle(title)
                .setTicker(title).setLargeIcon(largei).setContentIntent(contentIntent)
                .setContentIntent(contentIntent).setPriority(2).setStyle(new NotificationCompat.BigPictureStyle()
                        .setBigContentTitle(title).setSummaryText(message))
                .build();

    }
    notification.bigContentView = contentView;
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // Play default notification sound
    notification.defaults |= Notification.DEFAULT_SOUND;

    mNotificationManager.notify(0, notification);


}

//==========bind intent for specific class=====
private Intent[] getIntent(String type, String id, Context context){
    Intent[] list = new Intent[2];
    switch (type) {
    case Constants.UpdateApp:

        /**
          * first intent will open play store for
          * update and second one will open the home page
          */
        try {
            Intent viewIntent = new Intent("android.intent.action.VIEW",
            Uri.parse("https://play.google.com/store/apps/details?id=com.tripoto"));

         Intent mIntent = new Intent(context, HomePageSlidingTab.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         mIntent.putExtra(Constants.isCalledFromParse, true);
         mIntent.putExtra(Constants.ParseAnalytics, AnalyticsBundle);

         list[0] = mIntent;
         list[1] = viewIntent;
         }catch(Exception e) {} 

        break;
    case Constants.trips:
    case Constants.trip:
        /**
          * first intent will open trip page for
          * update and second one will open the home page
          */


        Intent notificationIntent = new Intent(context, TripHomePage.class);
        notificationIntent.putExtra(Constants.ClickedTripIdKey, id);
        notificationIntent.putExtra(Constants.ParseAnalytics, AnalyticsBundle);
        notificationIntent.putExtra(Constants.isCalledFromParse, true);

         Intent mIntent = new Intent(context, HomePageSlidingTab.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         list[0] = mIntent;
         list[1] = notificationIntent;


        break;
    case Constants.users:
    case Constants.user:
        /**
          * first intent will open profile page for
          * update and second one will open the home page
          */
        notificationIntent = new Intent(context, ProfileHomePage.class);
         notificationIntent.putExtra(Constants.ClickedUserIdKey, id);
         notificationIntent.putExtra(Constants.ParseAnalytics, AnalyticsBundle);
         notificationIntent.putExtra(Constants.isCalledFromParse, true);

         Intent mIntent1 = new Intent(context, HomePageSlidingTab.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         list[0] = mIntent1;
         list[1] = notificationIntent;

        break;
    case Constants.blog:
        /**
          * first intent will open blog page for
          * update and second one will open the home page
          */
        notificationIntent = new Intent(context, BlogDetail.class);
         notificationIntent.putExtra(Constants.ClickedBlogId, id);
         notificationIntent.putExtra(Constants.ParseAnalytics, AnalyticsBundle);
         notificationIntent.putExtra(Constants.isCalledFromParse, true);

         Intent mIntent2 = new Intent(context, HomePageSlidingTab.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         list[0] = mIntent2;
         list[1] = notificationIntent;
        break;
    case Constants.stash:
        /**
          * first intent will open stash page for
          * update and second one will open the home page
          */
        notificationIntent = new Intent(context, InStashTrips.class);
         notificationIntent.putExtra(Constants.ClickedTripkeyword, id);
         notificationIntent.putExtra(Constants.ParseAnalytics, AnalyticsBundle);
         notificationIntent.putExtra(Constants.isCalledFromParse, true);

         Intent mIntent3 = new Intent(context, HomePageSlidingTab.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         list[0] = mIntent3;
         list[1] = notificationIntent;
        break;
    case Constants.publish_my_trip:
        /**
          * first intent will open create trip page for
          * update and second one will open the home page
          **/
        //======I've to use a blank intent coz of its size======:D
         notificationIntent = new Intent();
         Intent mIntent4 = new Intent(context, HomePageSlidingTab.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         mIntent4.putExtra(Constants.isCalledFromParse, true);
         mIntent4.putExtra(Constants.ParseAnalytics, AnalyticsBundle);
         mIntent4.putExtra(Constants.isCalledForCreateTrip, true);

         list[0] = mIntent4;
         list[1] = notificationIntent;

        break;
    }


    return list;

}

}

1 个答案:

答案 0 :(得分:0)

您正在抱怨,因为您的应用已挂起,但您正在这样做:

 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
 StrictMode.setThreadPolicy(policy);

故意阻止Android告诉您正在执行可能导致App UI挂起的操作!

在任何情况下,看起来你可以在一个单独的线程中运行代码(我无法看到任何UI更新,所以应该没问题)。你可以试试一个简单的runnable:

@Override
public void onPushReceive(final Context context, final Intent intent) {
    new Thread(new Runnable() {

        @Override
        public void run() {
              // do real onPushReceive stuff here
        }

    }).start();
}

甚至是一个简单的IntentService(他们真的不那么难用):

@Override
public void onPushReceive(final Context context, final Intent intent) {
    Intent serviceIntent = new Intent(context, com.example.MyNotificationService.class);
    serviceIntent.putExtra('com.example.mypushintent', intent)
    context.startService(serviceIntent);
}

// In MyNotificationService.java
public class MyNotificationService extends IntentService {
    @Override
    public void onHandleIntent(Intent serviceIntent) {
       Intent pushIntent = (Intent)serviceIntent.getParcelableExtra('com.example.mypushintent');
       // do stuff here
    }
}

在任何情况下,最好尽量减少直接在BroadcastReceivers中完成的工作,并将任何重负荷的东西卸载到线程或服务中。