2017-12-20 7 views
0

バッテリー関連のアプリを作成しています。 私は放送受信機は、マニフェストで宣言し作成しました:ブロードキャスト受信機からフォアグラウンドサービスを開始するにはどうすればよいですか?

マニフェスト:

<receiver android:name=".PowerConnectionReceiver"> 
     <intent-filter> 
      <action android:name="android.intent.action.ACTION_POWER_CONNECTED" /> 
      <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" /> 
     </intent-filter> 
</receiver> 

受信機:

public class PowerConnectionReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) { 
      Toast.makeText(context, "The device is charging", Toast.LENGTH_SHORT).show(); 
     } else { 
      intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED); 
      Toast.makeText(context, "The device is not charging", Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 

私はフォアグラウンド通知(のようなthis 1)を追加したい しかし、どのように、私がすべき放送受信機から追加しますか? (つまり、どのように私は、放送受信機からサービスを開始することができますか?)

答えて

0

onReceiveで()サービス開始:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 
    startForeground(1, new Notification()); 
} 

:そのような何かを作る

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 
    context.startForegroundService(intent); 
} else { 
    context.startService(intent); 
} 

とサービスのonCreate(中に)いくつかのメーカーはAndroid Nにバックポートを持っているので、この新しいバックグラウンド制限があります。そのため、このAPIもサポートしています。

関連する問題