我有一个名为MainActivity.java的活动,其中包含自定义通知生成器。这是代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bcustomnotify = (Button) findViewById(R.id.customnotification);
bcustomnotify.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
CustomNotification();
}
});
}
public void CustomNotification() {
// Using RemoteViews to bind custom layouts into Notification
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.customnotification);
// Set Notification Title
String strtitle = getString(R.string.customnotificationtitle);
// Set Notification Text
String strtext = getString(R.string.customnotificationtext);
// Open NotificationView Class on Notification Click
Intent intent = new Intent(this, NotificationView.class);
// Send data to NotificationView Class
intent.putExtra("title", strtitle);
intent.putExtra("text", strtext);
// Open NotificationView.java Activity
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
// Set Icon
.setSmallIcon(R.mipmap.ic_launcher)
// Set Ticker Message
.setTicker(getString(R.string.customnotificationticker))
// Dismiss Notification
.setOngoing(true)
// Set PendingIntent into Notification
.setContentIntent(pIntent)
// Set RemoteViews into Notification
.setContent(remoteViews);
// Locate and set the Image into customnotificationtext.xml ImageViews
remoteViews.setImageViewResource(R.id.imagenotileft, R.mipmap.ic_launcher);
remoteViews.setImageViewResource(R.id.imagenotiright, R.mipmap.ic_launcher);
// Locate and set the Text into customnotificationtext.xml TextViews
remoteViews.setTextViewText(R.id.title, getString(R.string.customnotificationtitle));
remoteViews.setTextViewText(R.id.text, getString(R.string.customnotificationtext));
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0, builder.build());
}
}
我在另一个名为anotherActivity.java的活动中有一个类,如下所示:
public class anotherActivity extends Activity {
// some code
}
现在问题是
是否可以在点击MainActivity通知后运行其他活动的类而不实际将另一个活动作为待处理意图打开?
答案 0 :(得分:2)
是否可以在点击MainActivity通知后运行另一个活动的类而不实际将另一个活动作为待处理意图打开?
没有
如果您想点击Notification
来执行没有可见用户界限的操作,请不要在getActivity()
上使用PendingIntent
。使用getService()
或getBroadcast()
并路由到相应的组件。
如果您想要点按Notification
以显示一项活动(显然名为NotificationView
),并且还从AnotherActivity
执行某项操作,那么AnotherActivity
应该合并到NotificationView
中,或者将公共代码重构为另一个类或其他类。您的PendingIntent
可以做一件事:开始活动,启动服务或发送广播。