从一个BroadcastReceiver来MainActivity传递数据的正常工作只有一次 [英] Passing data from a BroadcastReceiver to MainActivity works correctly only once

查看:203
本文介绍了从一个BroadcastReceiver来MainActivity传递数据的正常工作只有一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 PushNotificationReceiver(扩展的BroadcastReceiver) MainActivity 。接收器发送一些数据(例如字符串值的新值)通过<$ C $到 MainActivity C>意图。然后 MainActivity 更新其的TextView 此值。 这工作得很好,直到我改变这个的TextView 值设置为其他值(例如重新设置为不定的)和移动活动到背景,并再次前景。该 MainActivity 恢复其的TextView 包含的新值 不过,我希望它是不定的 - 这就是问题所在

什么是错我的应用程序?

整个原计划在这里可以下载

下面是我的MainActivity code

 私人TextView的tvValue;
私人的EditText etNewValue;

@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);

    tvValue =(TextView中)findViewById(R.id.value);
    etNewValue =(EditText上)findViewById(R.id.new_value);

    findViewById(R.id.reset).setOnClickListener(新OnClickListener(){
        @覆盖
        公共无效的onClick(视图v){
            tvValue.setText(getResources()的getString(R.string.not_specified));
        }
    });

    findViewById(R.id.send_notification).setOnClickListener(新OnClickListener(){
        @覆盖
        公共无效的onClick(视图v){
            sendNotification的(etNewValue.getText()的toString());
        }
    });

    processDataFromBroadcast(getIntent());
}

@覆盖
公共无效onNewIntent(意向意图){
    super.onNewIntent(意向);
    processDataFromBroadcast(意向);
}

私人无效sendNotification的(字符串值){
    NotificationManager mNotificationManager =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

    字符串标题=原应用Notif;

    通知通知=新的通知(
            android.R.drawable.ic_notification_overlay,
            标题,
            System.currentTimeMillis的());
    notification.flags | = Notification.FLAG_AUTO_CANCEL;

    上下文CTXAPP = getApplicationContext();

    意图notificationIntent =新意图()
        .setAction(PushNotificationReceiver.ACTION_NOTIFICATION)
        .putExtra(价值,价值);
    PendingIntent contentIntent = PendingIntent.getBroadcast(
            CTXAPP,
            0,
            notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    notification.setLatestEventInfo(
            CTXAPP,
            标题,
            值,
            contentIntent);

    notification.audioStreamType = AudioManager.STREAM_NOTIFICATION;

    mNotificationManager.notify(1,通知);
}

私人无效processDataFromBroadcast(意向意图){
    如果(!intent.hasExtra(价值)){
        返回;
    }

    字符串VAL = intent.getStringExtra(价值);

    tvValue.setText(VAL); //更新我的活动的样子
}
 

PushNotificationReceiver

 私有静态最后弦乐LOG_CAT =PushNotificationReceiver;
静态最后弦乐ACTION_NOTIFICATION =com.mobiwolf.proto.NOTIFICATION_RECEIVER;

@覆盖
公共无效的onReceive(上下文的背景下,意图意图){
    如果(!intent.getAction()。等于(ACTION_NOTIFICATION)){
        返回;
    }

    字符串值= intent.getStringExtra(价值);

    Log.d(LOG_CAT,接收通知消息:+值); //日志始终包含发送的第一时间的价值

    意图I =新意图();
    i.setClass(背景下,MainActivity.class);
    i.putExtra(价值,价值);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    context.startActivity(ⅰ);
}
 

和清单

 &LT;接收器的Andr​​oid版本:NAME =com.mobiwolf.proto.PushNotificationReceiver&GT;
        &LT;意向滤光器&gt;
            &lt;作用机器人:名称=com.mobiwolf.proto.NOTIFICATION_RECEIVER/&GT;
        &所述; /意图滤光器&gt;
    &LT; /接收器&GT;

    &LT;活动机器人:名称=。MainActivity
              机器人:标签=@字符串/ APP_NAME
              机器人:launchMode =singleTask&GT;
        &LT;意向滤光器&gt;
            &lt;作用机器人:名称=android.intent.action.MAIN/&GT;
            &LT;类机器人:名称=android.intent.category.LAUNCHER/&GT;
        &所述; /意图滤光器&gt;
    &LT; /活性GT;
 

解决方案

为了解决这个问题,我添加全局静态触发

  / **
  *该类触发pushnotification是否由MainActivity处理
  *(preventing处理这个推送通知的两倍时,MainActivity
  *被移动到背景,并从背景恢复
  * /
  公共final类PushNotifHandledTrigger {
私有静态布尔办理=真;

公共静态布尔wasHandled(){
    返回处理;
}

公共静态无效套(){
    办理=真;
}

公共静态无效的复位(){
    处理= FALSE;
}
  }
 

然后startActivity之前,我做复位此触发和操作后设置(当然执行处理只有当触发未设置)

I have a PushNotificationReceiver (extends BroadcastReceiver) and MainActivity. The receiver sends some data (for example string value "New value") to the MainActivity via an Intent. Then MainActivity updates its TextView with this value. This works fine until I change this TextView value to some other value (for example reset it to "UNSPECIFIED") and move the activity to background and to foreground again. The MainActivity is restored and its TextView contains "New value", however I expected it to be "UNSPECIFIED" - this is the problem.

What is wrong with my app?

The whole proto project may be downloaded here.

Here is my MainActivity code

private TextView tvValue;
private EditText etNewValue;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tvValue = (TextView)findViewById(R.id.value);
    etNewValue = (EditText)findViewById(R.id.new_value);

    findViewById(R.id.reset).setOnClickListener(new OnClickListener() {         
        @Override
        public void onClick(View v) {
            tvValue.setText(getResources().getString(R.string.not_specified));
        }
    });

    findViewById(R.id.send_notification).setOnClickListener(new OnClickListener() {         
        @Override
        public void onClick(View v) {
            sendNotification(etNewValue.getText().toString());
        }
    });

    processDataFromBroadcast(getIntent());        
}

@Override
public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    processDataFromBroadcast(intent);
}

private void sendNotification(String value){
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    String title = "Proto App Notif";

    Notification notification = new Notification(
            android.R.drawable.ic_notification_overlay,
            title,
            System.currentTimeMillis());
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    Context ctxApp = getApplicationContext();

    Intent notificationIntent = new Intent()
        .setAction(PushNotificationReceiver.ACTION_NOTIFICATION)
        .putExtra("value", value);
    PendingIntent contentIntent = PendingIntent.getBroadcast(
            ctxApp, 
            0, 
            notificationIntent, 
            PendingIntent.FLAG_UPDATE_CURRENT);     

    notification.setLatestEventInfo(
            ctxApp,
            title,
            value,
            contentIntent);

    notification.audioStreamType = AudioManager.STREAM_NOTIFICATION;

    mNotificationManager.notify(1, notification);           
}

private void processDataFromBroadcast(Intent intent) {
    if (!intent.hasExtra("value")){
        return;
    }

    String val = intent.getStringExtra("value");

    tvValue.setText(val); // Updating my activity look
}

PushNotificationReceiver

private static final String LOG_CAT = "PushNotificationReceiver";
static final String ACTION_NOTIFICATION = "com.mobiwolf.proto.NOTIFICATION_RECEIVER";

@Override
public void onReceive(Context context, Intent intent) {
    if (!intent.getAction().equals(ACTION_NOTIFICATION)) {
        return;
    }

    String value = intent.getStringExtra("value");

    Log.d(LOG_CAT, "Received notification message: "+value); // Log always contains the value sent on first time

    Intent i = new Intent();
    i.setClass(context, MainActivity.class);
    i.putExtra("value", value);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    context.startActivity(i);
}

And manifest

    <receiver android:name="com.mobiwolf.proto.PushNotificationReceiver">
        <intent-filter>
            <action android:name="com.mobiwolf.proto.NOTIFICATION_RECEIVER" />
        </intent-filter>
    </receiver>    

    <activity android:name=".MainActivity"
              android:label="@string/app_name"
              android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

解决方案

For solving this problem I added global static trigger

  /**
  * This class triggers whether pushnotification was handled by MainActivity
  * (Preventing handling this push notification twice when the MainActivity 
  * is moved to background and restored from background
  */
  public final class PushNotifHandledTrigger {
private static boolean handled = true;

public static boolean wasHandled(){
    return handled;
}

public static void set(){
    handled = true;
}

public static void reset(){
    handled = false;
}
  }

Then before startActivity I do reset this trigger and set after handling (and of course perform handling only if trigger is not set)

这篇关于从一个BroadcastReceiver来MainActivity传递数据的正常工作只有一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆