即使应用关闭,如何启动Android通知?

时间:2014-01-31 13:35:10

标签: android notifications alarmmanager

请帮帮我.., 即使应用关闭,如何启动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编程的新手:)

1 个答案:

答案 0 :(得分:0)

  • * /试试这个,你必须使用广播接收器。 并且在清单文件中添加此内容,

     <uses-permission android:name="android.permission.WAKE_LOCK" />
    

//

     private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
        // Waking up mobile if it is sleeping
        WakeLocker.acquire(getApplicationContext());

        /**
         * Take appropriate action on this message
         * depending upon your app requirement
         * For now i am just displaying it on the screen
         * */

        // Showing received message
        lblMessage.append(newMessage + "\n");           
        Toast.makeText(getApplicationContext(), "New Message: " +       newMessage, Toast.LENGTH_LONG).show();

        // Releasing wake lock
        WakeLocker.release();
    }};

//

    public abstract class WakeLocker {
    private static PowerManager.WakeLock wakeLock;

    public static void acquire(Context context) {
    if (wakeLock != null) wakeLock.release();

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
            PowerManager.ACQUIRE_CAUSES_WAKEUP |
            PowerManager.ON_AFTER_RELEASE, "WakeLock");
    wakeLock.acquire();
    }

    public static void release() {
    if (wakeLock != null) wakeLock.release(); wakeLock = null;
    }
    }

// 您必须在MainActivity中编写广播接收器的代码。因为在发生通知时你会调用mainactivity。