0

我正在尝试从另一个活动中的文本视图中获取内容以显示在通知栏消息中。它有效,但不正确。来自 textview 的字符串确实显示在通知中,我通过捆绑来自其他活动的 textview 的信息来做到这一点,然后让通知管理器获取捆绑包。当启动另一个活动时会出现问题,它会触发通知,因为活动中的最后一块代码进行捆绑和发送,这会导致通知触发,忽略设置的触发时间。所以我的问题是让通知从另一个活动中获取字符串的最佳和最简单的方法是什么?这是活动,这就是问题所在。它自己触发通知:

    import java.io.IOException;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.widget.TextView;

public class DBTest2 extends Activity {

String scrNote;
TextView showBV;
NotificationManager nm;
DBAdapter dba;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dbtest_2);
    showBV = (TextView) findViewById(R.id.getBK_TV);

    nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    //---cancel the notification---
    try{
    nm.cancel(getIntent().getExtras().getInt("uID"));
    } catch (Exception e) {
        System.out.println("Error when cancelling: "+e.toString());
    }
    //---END cancel the notification---



    //---- SHOW IN NOTIFICATION------

    scrNote = showBV.getText().toString();
    Bundle moveScrNote = new Bundle();
    moveScrNote.putString("mSN", scrNote);
    Intent toNoteBody = new Intent(DBTest2.this, DisplayNotifications.class);
    toNoteBody.putExtras(moveScrNote);
    startActivity(toNoteBody);


    //---- END   SHOW IN NOTIFICATION------


}


}

这是通知管理器:

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

    //---get the notification ID for the notification; 
    // passed in by the MainActivity---
    int uID = getIntent().getExtras().getInt("uniqueID");

    //---PendingIntent to launch activity
    Intent noteI = new Intent("com.vee.search01.DBTEST2");
    noteI.putExtra("uniqueID", uID);

    PendingIntent herroIntent = 
        PendingIntent.getActivity(this, 0, noteI, 0);

    nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    long fireTime = System.currentTimeMillis();
    String noteTitle = "Notification Title";

    Bundle getNoteBody = getIntent().getExtras();
    String gotNoteBody = getNoteBody.getString("mSN");
    String noteBody = gotNoteBody;

    Notification note = new Notification(R.drawable.noteicon, noteTitle, fireTime);
    note.setLatestEventInfo(this, noteTitle, noteBody, herroIntent);
    note.defaults |= Notification.DEFAULT_SOUND;
    note.defaults |= Notification.FLAG_SHOW_LIGHTS;
    nm.notify(uID, note);
    finish();
}

}
4

1 回答 1

1

在活动之间传输内容的最佳方式是通过 Intent 中的附加内容发送。

如果您从 Activity A 发出通知,并且想在 Activity B 中处理它,则在 A 中创建通知并插入包含 Intent 的 PendingIntent 以启动 B。当通知显示并且用户单击它时,B 应该被辞退了。

如果要将通知文本从 B 发送到 A,请使用单独的 Intent。

如果您尝试将通知 Intent 的文本发送到 B 并显示通知,请将文本放入 Intent 的附加内容中。

此外,如果您使用的是平台的最新版本,请阅读通知的参考文档。它已被弃用,有利于通过 Notification.Builder 创建通知。一个优点是您可以将通知设置为自动取消,因此您不必在代码中取消它。

于 2012-06-07T23:47:26.557 回答