android的Service和Notification學習
阿新 • • 發佈:2019-02-12
package com.example.study; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; importandroid.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; public class ServiceDemo extends Service { public static NotificationManager notificationManager; Handler mHandler = new Handler() { public void handleMessage(Message msg) {switch (msg.what) { case 1: if (notificationManager == null) { addNotificaction(); } break; default: break; } } }; @Override public IBinder onBind(Intent intent) {return null; } @Override public void onCreate() { super.onCreate(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(1000 * 60); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Boolean b = detect(ServiceDemo.this); System.out.println(b); if (b) { Message msg = new Message(); msg.what = 1; mHandler.sendMessage(msg); } } } }).start(); } private void addNotificaction() { Notification notification = new Notification(R.drawable.ic_launcher, "Notification測試", System.currentTimeMillis()); notificationManager = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE); Intent startintent = new Intent(this, MainActivity.class); startintent.putExtra("data", "data"); PendingIntent pendingIntent02 = PendingIntent.getActivity(this, 0, startintent, 0); notification.setLatestEventInfo(this, "測試", "跳轉到主介面", pendingIntent02); notificationManager.notify(0, notification); } public boolean detect(Context con) { ConnectivityManager manager = (ConnectivityManager) con .getApplicationContext().getSystemService( Context.CONNECTIVITY_SERVICE); if (manager == null) { return false; } NetworkInfo networkinfo = manager.getActiveNetworkInfo(); if (networkinfo == null || !networkinfo.isAvailable()) { return false; } return true; } @Override public void onDestroy() { super.onDestroy(); Log.v("CountService", "on destroy"