How to start foreground notification ..
if your android version>=o then you have crate notification channel the best way to start create notification channel inside the App class
public class App extends Application {
public static final String channe_id="Location";
public static final String channel_id2="Backgroundlocation";
@Override
public void onCreate() {
super.onCreate();
SetChannelId(channe_id,"Location");
SetChannelId(channel_id2,"Background Location");
}
private void SetChannelId(String channleId,String channelName)
{
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new
NotificationChannel(channleId, channelName, NotificationManager.IMPORTANCE_HIGH);
channel.setLockscreenVisibility(1);
channel.setLightColor(getColor(R.color.purple_700));
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
}
}
}
in this example we are start the foreground service by using service class
public class Myservice extends Service {
private static int i=0;
private FusedLocationProviderClient mProviderClient;
private LocationRequest mLocationRequest;
private String longmessage="for ground service gg hjhg jhdj hdgf hdgfjd duygfd\" +\n" +
"djfhjdgf fguf hkj kmio uijuiiiiiiiiiii iuuuuuuuuu hhhhhhhhhhh\" +\n" +
"kokikkkkkkkkkkkkkkkkkkkkkkkkk ";
private LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
Location location = locationResult.getLastLocation();
setDataToserver(location);
}
};
private void setDataToserver(Location location) {
if (location != null) {
Log.d("service", "location :"+i + location.getLatitude());
i++;
/* Toast.makeText(getApplicationContext(), "location update " + location.getLatitude()
, Toast.LENGTH_SHORT).show();*/
} else {
/* Toast.makeText(getApplicationContext(), "not location update", Toast.LENGTH_SHORT).show();
Log.d("service", "location :not update");*/
}
}
@Override
public void onCreate() {
super.onCreate();
mProviderClient = LocationServices.getFusedLocationProviderClient(this);
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5 * 1000);
mLocationRequest.setFastestInterval(10 * 800);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(9,getNotification());
getUpdateLocation();
return START_STICKY;
}
private Notification getNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
App.channe_id);
builder.setPriority(NotificationManager.IMPORTANCE_HIGH);
builder.setContentTitle("Location running");
builder.setContentText(longmessage);
builder.setSubText("i am sub text");
builder.setSmallIcon(R.mipmap.ic_launcher_round);
builder.setStyle(new NotificationCompat.BigTextStyle().bigText("i am big text "+longmessage));
/* builder.setStyle(new NotificationCompat.InboxStyle().addLine("i am long1"+longmessage)
.addLine("i ma long2"+longmessage)
.setBigContentTitle("title"+longmessage)
.setSummaryText("coding@gmail.com"))
.setGroupSummary(true);*/
builder.setAutoCancel(false);
return builder.build();
}
private void getUpdateLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
stopForeground(true);
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
HandlerThread handlerThread =new HandlerThread("Myhandler");
handlerThread.start();
mProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper());
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceTask=new Intent(getApplicationContext(),this.getClass());
restartServiceTask.setPackage(getPackageName());
PendingIntent pendingIntent=PendingIntent.getService(this,3,restartServiceTask,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager=(AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime()+1000
,pendingIntent
);
startService(new Intent(this,Myservice.class));
Log.d("service","OnTaskRemoved");
super.onTaskRemoved(rootIntent);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
// Toast.makeText(getApplicationContext(), "service destory", Toast.LENGTH_SHORT).show();
if(mLocationCallback!=null)
{
Log.d("service","serivce destory:");
mProviderClient.removeLocationUpdates(mLocationCallback);
}
Log.d("service","serivce destory2:");
super.onDestroy();
}
start the forground service in MainActivity or U can stasrt from any activity as ur wish
mBinding.startservice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,Myservice.class);
Toast.makeText(getApplicationContext(), "service start", Toast.LENGTH_SHORT).show();
//this comment code is alos write
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
}else
{
startService(intent);
}*/
// startService(intent);
ContextCompat.startForegroundService(getApplicationContext(),intent);
//startService(intent);
}
});}
No comments:
Post a Comment