-1
請幫助我.., 即使應用程序關閉,如何啓動Android通知?即使應用程序關閉,如何啓動Android通知?
這是我在MainActivity.class代碼:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(MainActivity.this, myService.class));
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent i = new Intent(this, myService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
am.cancel(pi);
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 60000, 60000, pi);
..............
...........
&這是我在myService.class代碼:
import java.util.Date;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
public class myService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleIntent(intent);
return START_NOT_STICKY;
}
private NotificationManager nm;
private WakeLock mWakeLock;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
mWakeLock.release();
}
@SuppressWarnings("deprecation")
private void showNotification() {
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,
"Notification Ticker", System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL;
Date date = new Date(System.currentTimeMillis());
Intent i = new Intent(this, MainActivity.class);
i.putExtra("notification",
"This is the Notification " + date);
i.putExtra("notifiedby", "xyz");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this, "xyz",
"This is the Notification", contentIntent);
nm.notify(R.string.service_started, notification);
}
private class PollTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
showNotification();
return null;
}
@Override
protected void onPostExecute(Void result) {
stopSelf();
}
}
@SuppressWarnings("deprecation")
private void handleIntent(Intent intent) {
// obtain the wake lock
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"NotificationsService");
mWakeLock.acquire();
// check the global background data setting
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
if (!cm.getBackgroundDataSetting()) {
stopSelf();
return;
}
new PollTask().execute();
}
}
我不會在所有的工作,我不不知道爲什麼 所以請幫助我,我是Android編程的新手:)
我應該在哪類寫這段代碼? – user3199244
您必須在MainActivity中編寫廣播接收器的代碼。因爲你在通知來臨時調用主要活動。 –