【问题标题】:Set text on textView in background process在后台进程中在 textView 上设置文本
【发布时间】:2016-11-13 17:27:59
【问题描述】:

所以,我的应用程序具有 BroadcastReceiver 并接收来自其他应用程序的通知。问题是,我收到一条消息,通过 Toast 在手机中显示它,但我想将它设置为在我的 TextView 上可见。我的整个应用程序中只有两个类。

我的接收器是我自己的类,它扩展了 BroadcastReceiver,它的 onReceive 方法如下所示:

@Override
public void onReceive(Context context, Intent intent) {
    String value =  intent.getExtras().getString("hiddenMessage");
    MainActivity.getInstace().updateTheTextView(value);
}

这是更新 textView 的方法的代码。该方法在 MainActivity 类中:

public void updateTheTextView(final String textFromNotification) {
    final Context context = this;

    Toast toast = Toast.makeText(context, "Message received: " + textFromNotification, Toast.LENGTH_LONG);
    toast.show();

    ((Activity) context).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            textV1.setText(textFromNotification);
        }
    });
}

问题是,当我从一个应用程序发送通知并在此处接收时,文本不可见。它仅在此应用程序打开时可见。当我的应用程序未打开时,如何将文本设置为字段?将消息存储到某个类字段并在 onResume 方法中使用 setText()?

【问题讨论】:

  • 上面的代码在哪里?广播接收器实例是否在同一个类中创建和注册/注销?
  • 将其存储在 sharedpreferences 中并加载 onCreate
  • @clownba0t 我更新了我的问题并添加了更多信息。
  • MainActivity.getInstace() [sic] 方法有什么作用?

标签: android broadcastreceiver


【解决方案1】:

在获取字符串值后的 onReceive 方法中,像这样将其存储在 sharedPreference 中

public void saveInSharedPreferences(String value){
    SharedPreferences sharedpreferences = getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString("variable",value);//your String value
    editor.commit();
}

您的 onReceive 方法将类似于

public void onReceive(Context context, Intent intent) {
    String value =  intent.getExtras().getString("hiddenMessage");
    saveInSharedPreferences(value);
}

在您的 Activity 的 onCreate 方法中

protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     String value = getValueFromSharedPreference();
     if(value != null){
          textview.setText(value);
     }
}

getValueFromSharedPreference 方法

public String getValueFromSharedPreference(){
         SharedPreferences sharedpreferences = getSharedPreferences("sharedPref", Context.MODE_PRIVATE);

         return sharedpreferences.getString("variable",null);
}

现在,如果您想在应用打开时更新 Textview
试试这个

public void onReceive(Context context, Intent intent) {
    String value =  intent.getExtras().getString("hiddenMessage");
    saveInSharedPreferences(value);
    Intent intent = new Intent("broadcast");
    intent.putExtra("variable",value);
    context.sendBroadCast(intent);
}

然后在你的 Activity 的 oncreate 方法中

registerReceiver(broadcastReceiver, new IntentFilter("broadcast"));

然后在 oncreate 方法之外的 Activity 类中

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

          String value = intent.getStringExtra("variable");
          textview.setText(value);
    }
};

或者你甚至可以使用这个接口解决方案:https://stackoverflow.com/a/26268569/6799807

【讨论】:

  • 据我了解,这将在我打开应用程序时更新我的​​ textView。如果我的应用已经打开了怎么办?
  • 另一个问题是,如何在仅扩展 BroadcastReceiver 的单独类中使用方法 getSharedPreferences? getSharedPreferences 来自 Context...?
  • 您可以将 saveInSharedPreferences 方法放在扩展 BroadcastReceiver 类的类中,然后在 sharedpreference 使用上下文中
  • 还有一个问题:如何从 onReceive 方法创建通知,以便它打开我的应用程序并显示消息?
【解决方案2】:

首先在 onRecieve 方法中将详细信息保存在 sql 中

   private void saveNotification(String msg) {
   //notification_sql class to save detail
    Notification_sql n=new Notification_sql(getApplicationContext());
    Notification_detail notification_detail=new Notification_detail();
    //notification detail model class to set and get get detail
    notification_detail.setData(msg);
    n.adddetail(notification_detail);
    }

在数据库中第二次保存细节

    public String adddetail(Notification_detail dataval){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(DATE_OF_ENTRY,dataval.getData());
    // Inserting Row
    db.insert(TABLE_NAME, null, values);
    db.close(); // Closing database connection
    return null;
    }

在 Main Activity 中使用任务调度器获取数据

    scheduleTaskExecutor= Executors.newScheduledThreadPool(5);
    // This schedule a task to run every 10 minutes:
       scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        public void run() {
            // If you need update UI, simply do this:
            runOnUiThread(new Runnable() {
                public void run() {
                    //update text view
                    Notification_sql meter_data=new Notification_sql(MapsActivity.this);
                    //getting detail from database which is saved just after message delivery
                    List<Notification_detail> contacts = meter_data.getDetail();
                    //System.out.println(contacts);
                    for (Notification_detail cn : contacts) {
                        String data=cn.getData();

                       txtdetail.setText(data)
                    }
                }
            });
        }
      }, 0, 10, TimeUnit.SECONDS);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 2011-08-04
    • 2021-11-07
    • 2020-03-01
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多