回答

1

請不要每隔X分鐘從網絡服務中提取一個頁面 - 這會耗盡電量,使用Google Cloud Messaging(原C2DM - 雲設備消息傳遞)來獲取您的信息更新 - 它非常輕巧並且非常高效,併爲所有應用程序共享一個現有數據連接。

+0

感謝您的建議,但中心問題是創建通知的後臺服務,我不知道該怎麼做 – user1435753

+0

您可能會得到一個'NotificationManager'並使用它來創建通知,請參閱下面的答案 – lenik

1

NotificationManager似乎是你在找什麼東西。

+0

我知道,但是什麼東西產生了nofication ?,我想需要一個處理程序來創建通知,我不知道它是怎麼做的 – user1435753

+0

你應該真正閱讀Android文檔。請參閱服務文檔:http://developer.android.com/guide/components/services.html。但是正如lenik所說,Cloud To Device Messaging絕對是更好的選擇。 – SimonSays

0

首先你需要一個廣播接收器(它自己的類中,加在清單一些代碼)的是反作用於USER_PRESENT動作(當用戶解鎖屏幕)或BOOT_COMPLETED(當手機完成加載操作系統和所有其他的東西)。啓動激活廣播,廣播啓動服務。在服務的onStartCommand()方法內部,每隔X分鐘運行一次到web服務的連接。你的服務應該實現AsyncTask來連接到Web服務。在該任務的onCompleted()方法中,您可以調用通知。

清單:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/> 
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> 
<receiver android:name="classes.myReceiver" >   
      <intent-filter> 
       <action android:name="android.intent.action.BOOT_COMPLETED" /> 
       <category android:name="android.intent.category.DEFAULT" /> 
      </intent-filter> 
     </receiver> 


     <service android:name="classes.myService">   
     </service> 

類:

public class myReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context ctx, Intent intent) {  
     Intent service = new Intent(ctx, myService.class); 
     if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)||intent.getAction().equals(Intent.ACTION_USER_PRESENT)||intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { 
      ctx.startService(service); 
      } 
     if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { 
      ctx.stopService(service); 
      } 
     } 
} 

示例通知

private void showNotification() {    
     NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     notificationBuilder = new NotificationCompat.Builder(this); 
     notificationBuilder.setContent(getNotificationContent()); 
     notificationBuilder.setOngoing(true); 

      notificationBuilder.setTicker("Hello"); 
      notificationBuilder.setSmallIcon(R.drawable.notif_icon); 

     mNotificationManager.notify(R.id.notification_layout, notificationBuilder.build()); 
     } 

private RemoteViews getNotificationContent() { 

      RemoteViews notificationContent = new RemoteViews(getPackageName(), R.layout.keyphrase_recogniser_notification); 
     notificationContent.setTextViewText(R.id.notification_title, "title"); 
      notificationContent.setTextViewText(R.id.notification_subtitle, "subtitle"); 
return notificationContent; 
      } 

這是一個廣泛的指南,如果你需要更具體的代碼讓我們知道。