我的android studio有问题。当我关闭主应用程序时,我无法显示来自服务的通知。有没有办法做到这一点?
这是我的应用: 它显示15秒倒计时的通知
主要活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View V) {
Intent intent = new Intent(this, NotifyActivity.class);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notification")
.setContentText("Text of notification")
.setTicker("Notify");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this)
.addParentStack(NotifyActivity.class)
.addNextIntent(intent);
PendingIntent pIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pIntent);
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, builder.build());
Intent i = new Intent(this, MyService.class);
startService(i);
}
为MyService
public class MyService extends IntentService {
public MyService() {
super("MyWorkThread");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Hey!", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
synchronized (this) {
try {
final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
for (int i=0; i<15; i++) {
int time = 15 - i;
Intent intent1 = new Intent(this, NotifyActivity.class);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Time left: " + time)
.setContentText("Text of notification");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this)
.addParentStack(NotifyActivity.class)
.addNextIntent(intent1);
PendingIntent pIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pIntent);
nm.notify(0, builder.build());
wait(1000);
}
nm.cancel(0);
} catch (InterruptedException e) { e.printStackTrace(); }
}
}
@Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "Aaaaand it's gone!", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
}
NotifyActivity
public class NotifyActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notify);
}
}
AndroidManifest中的服务:
<service android:name=".MyService"
android:enabled="true"
android:exported="false"/>