6

我正在使用cordova來構建我的android應用程序。由於android殺死服務,我綁定服務與通知,以避免服務死亡。Cordova - 通知後臺運行服務

這裏是我的方法,我怎麼綁定服務,併發出通知

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    context = this.getApplicationContext(); 
    notifyService(); 

    return START_NOT_STICKY; 
} 

private void notifyService() { 
    String package_name = this.getApplication().getPackageName(); 

    Intent notificationIntent = new Intent(this, MainActivity.class); 
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 

    Bitmap icon = BitmapFactory.decodeResource(getResources(), 
      this.getApplication().getResources().getIdentifier("icon", "drawable-hdpi", package_name)); 

    Notification notification = new NotificationCompat.Builder(this) 
      .setContentTitle("Smart Home") 
      .setContentText("Smart Home running in background") 
.setSmallIcon(this.getApplication().getResources().getIdentifier("icon", "drawable-hdpi", package_name)) 
      .setContentIntent(pendingIntent) 
      .setOngoing(true) 
      .build(); 

    startForeground(notificationId, notification); 
} 

這裏的生成

enter image description here

通知的輸出,但通知的標題是不是我設置。另外,當我點擊這個通知時,它正在移動到應用信息活動。但我想轉移到我的主要活動。

有沒有人遇到過這個問題?或者我的代碼需要更改cordova?

+0

你想科爾多瓦通知應用程序作爲服務在後臺?這是你的問題嗎? – Gandhi

+0

@甘地我從我的插件啓動一項服務。我不希望Android殺死它。所以我使用前臺通知。我可以通知它通知,但生成的通知不是我的通知 –

+0

你看看這個插件是否感到羞恥 - https://github.com/Red-Folder/bgs-core/wiki/Build-your-own-Background-Service – Gandhi

回答

3

想通了千呼萬喚試。問題出在我待處理的意圖活動名稱上。下面的代碼爲我工作

String package_name = this.getApplication().getPackageName(); 
Intent notificationIntent = context.getPackageManager().getLaunchIntentForPackage(package_name); 
+0

接受[Naresh Kumar](http://stackoverflow.com/a/42759500/984830)給出的解決方案的答案有什麼問題? –

+0

@NickCardoso對不起,我沒有指定什麼是我的待決意圖錯誤。我傳遞給pendingIntent的NotificationIntent不正確。它應該是Intent notificationIntent = context.getPackageManager()。getLaunchIntentForPackage(package_name); –

+0

很好的解釋,你應該限制你的答案,只是改變的線條,使其更清晰 –

3

當我點擊這個通知時,它正在移動到應用信息活動。但我想搬到我的主要活動此行

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 

實現這一 改變這一行

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

希望它可以幫助你