我的应用中有两项活动:
A - 登录活动
B - 主要活动
当用户点击活动A中的登录按钮时,我正在启动服务。在服务的onCreate()方法中,我像这样启动活动B:
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat
.Builder(getApplicationContext());
builder.setContentIntent(pendingIntent);
builder.setContentTitle("Activity B in foreground service");
builder.setSmallIcon(R.drawable.ic_launcher);
startForeground(1, builder.build());
问题在于活动B的启动最小化。我必须按通知栏中的服务按钮才能使我的活动最大化(填满屏幕)。我怎样才能以正常方式从服务中启动Activity B-而不是最小化它(放到后台)?
答案 0 :(得分:1)
您的代码根本不会实际启动活动B.它只需创建一个Notification
,如果用户选择,将启动活动B.
如果您想实际启动活动B,请执行以下操作:
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Now launch the activity immediately
startActivity(notificationIntent);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat
.Builder(getApplicationContext());
... (rest of your code here)
答案 1 :(得分:0)
问题已在android start activity from service
中得到解答public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
http://developer.android.com/training/basics/firstapp/starting-activity.html
答案 2 :(得分:0)
最后我找到了解决方案:
服务类中的onCreate()方法:
@Override
public void onCreate() {
Intent notificationIntent = new Intent(getBaseContext(), MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
getApplication().startActivity(notificationIntent);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat
.Builder(getApplicationContext());
builder.setContentIntent(pendingIntent);
builder.setContentTitle("Activity B runs in a foreground service");
builder.setSmallIcon(R.drawable.ic_launcher);
startForeground(1, builder.build());
}
在AndroidManifest.xml中,在Activity元素中添加以下行:
android:launchMode="singleTop"