How do I use the service on Android Top 5 - service

I've used a service in my program but the top 5 Android phone goes to sleep as soon as the service does nothing.
It works on Android 4 without any problems.
pls help me.
in Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this , MyService.class));
}
}
in Service
public class MyService extends android.app.Service {
private PowerManager pm;
private WifiManager wm;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//do something code
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
if (android.os.Build.VERSION.SDK_INT >= 21) {
pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.PARTIAL_WAKE_LOCK), "TAG");
wakeLock.acquire();
wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiManager.WifiLock lock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "LockTag");
lock.acquire();
Intent restartServiceIntent = new Intent(getApplicationContext(),
MyService.class);
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(
getApplicationContext(), 0, restartServiceIntent,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext()
.getSystemService(Context.ALARM_SERVICE);
long thirtySecondsFromNow = 1000;
alarmService.set(AlarmManager.RTC_WAKEUP, thirtySecondsFromNow, restartServicePendingIntent);
ComponentName receiver = new ComponentName(getApplicationContext(), MyService.class);
PackageManager pm = getApplicationContext().getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
super.onTaskRemoved(rootIntent);
}
}
}
in Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.service">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="false"
android:label="my"
android:largeHeap="true"
android:stopWithTask="false" />
</application>

Related

Scoped Storage won't allow FileInputStream access to file in DOWNLOADS, is there a workaround?

I import data from a downloaded spreadsheet into a Room database. This is what I need to do :
String filePath = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath();
String fileName = context.getString(R.my_file_name);
File importFile = new File(filePath + File.separator, fileName);
try {
FileInputStream stream = new FileInputStream(importFile);
// do stuff
} catch (Exception e1) {e1.printStackTrace();}
So, this doesn't work anymore(?) I haven't been able to find a concise explanation (in JAVA) of how to accomplish this simple operation going forward without asking for the MANAGE_EXTERNAL_STORAGE permission (an unacceptable solution) Help from the gurus?
So, need to set up intent in manifest, and leave old permissions for legacy android
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
<application
android:requestLegacyExternalStorage="true"
>
<activity
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
in mainActivity, set up file picker, create method to launch the picker, and create method to process picker result.
Main Activity :
private ActivityResultLauncher<Intent> launchFilePicker;
public File importFile;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filePath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).
getAbsolutePath();
launchFilePicker = registerForActivityResult(
new ActivityResultContract<Intent, Uri>() {
#NonNull
#Override
public Intent createIntent(#NonNull Context context, Intent input) {
return input;
}
#Override
public Uri parseResult(int resultCode, #Nullable Intent result) {
if (result == null || resultCode != Activity.RESULT_OK) {
return null;
}
return result.getData();
}
},
this::getFileFromUri);
...
public void launchFileFinder() {
Intent pickerIntent = new Intent(ACTION_OPEN_DOCUMENT);
pickerIntent.addCategory(Intent.CATEGORY_OPENABLE);
pickerIntent.setType(" your mime type ");
pickerIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
launchFilePicker.launch(pickerIntent);
}
...
public void getFileFromUri(Uri result) {
String fileName = context.getString(R.my_file_name);
File importFile = new File(filePath + File.separator, fileName);
InputStream stream = null;
try {
stream = AppMainActivity.this.getContentResolver().openInputStream(result);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (stream != null) {
try {
FileInputStream stream = new FileInputStream(importFile);
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
}
}
}
}

Mapbox navigation project with LED

Working on a project on Android studio to turn on LED via Bluetooth using mapbox turn-by-turn navigation directions. To be specific turn on left LED on the "To the right" direction arrow is displayed or any other is displayed. Is it possible to do?
MainActivity.java
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.services.android.location.LostLocationEngine;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import com.mapbox.services.android.navigation.ui.v5.NavigationViewOptions;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.services.android.telemetry.location.LocationEngine;
import com.mapbox.services.android.telemetry.location.LocationEngineListener;
import com.mapbox.services.android.telemetry.location.LocationEnginePriority;
import com.mapbox.services.android.telemetry.permissions.PermissionsListener;
import com.mapbox.services.android.telemetry.permissions.PermissionsManager;
// classes to calculate a route
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LocationEngineListener, PermissionsListener {
private MapView mapView;
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationLayerPlugin locationPlugin;
private LocationEngine locationEngine;
private Location originLocation;
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
private Button button;
// variables for calculating and drawing a route
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng point) {
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
};
});
};
});
button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Point origin = originPosition;
Point destination = destinationPosition;
// Pass in your Amazon Polly pool id for speech synthesis using Amazon Polly
// Set to null to use the default Android speech synthesizer
String awsPoolId = null;
boolean simulateRoute = false;
NavigationViewOptions options = NavigationViewOptions.builder()
.origin(origin)
.destination(destination)
.awsPoolId(awsPoolId)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Create an instance of LOST location engine
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(LocationLayerMode.TRACKING);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings( {"MissingPermission"})
private void initializeLocationEngine() {
locationEngine = new LostLocationEngine(MainActivity.this);
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#Override
#SuppressWarnings( {"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStop();
}
mapView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onConnected() {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/startButton"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:padding="5px"
android:layout_margin="20px"
android:text="Start navigation"
android:background="#color/mapboxGrayLight"
android:textColor="#color/mapboxWhite"
android:enabled="false"/>
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
mapbox:mapbox_cameraTargetLat="38.9098"
mapbox:mapbox_cameraTargetLng="-77.0295"
mapbox:mapbox_styleUrl="mapbox://styles/mapbox/streets-v10"
mapbox:mapbox_cameraZoom="12" />
</RelativeLayout>
build.gradle
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.adailtonribeiro.android_navigator"
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
mavenCentral()
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.mcxiaoke.volley:library:1.0.19'
implementation ('com.mapbox.mapboxsdk:mapbox-android-sdk:5.5.0#aar') {
transitive=true
}
implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.11.1'
implementation ('com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.11.1') {
transitive = true
}
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-locationlayer:0.4.0'
}
buildscript {
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.adailtonribeiro.android_navigator">
<!-- Coarse location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- Or fine location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

how to send location in android device to server (php) automaticlly

I have to send location(latitude & longitude) from android device to server (php) automatically (every 2 min)
and for this work I am using JobSchedulerCompat for service to send location.
But after this send locations to the server only after the application run, I want to send locations to the server continuously.
How can I achieve that?
Here is my code so far:
GpsTracker.java
public class GPSTracker extends Service {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
try {
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){
ex.printStackTrace();
}
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListenerNetwork);
Toast.makeText(mContext,"Network Enabled",Toast.LENGTH_SHORT).show();
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListenerGps);
//Log.d("GPS Enabled", "GPS Enabled");
Toast.makeText(mContext,"GPS Enabled",Toast.LENGTH_SHORT).show();
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(locationListenerGps);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MyService.java
public class MyService extends JobService{
String code;
#Override
public boolean onStartJob(JobParameters params) {
code=readsavefile(getApplicationContext(),"Code2","Error");
//Toast.makeText(getApplicationContext(),code,Toast.LENGTH_SHORT).show();
new SendLocation(this,params,getApplicationContext()).execute(code);
//Toast.makeText(getApplicationContext(),"Start",Toast.LENGTH_SHORT).show();
//jobFinished(params, false);
return true;
}
public static String readsavefile(Context context,String pname,String dvalue){
SharedPreferences shared=context.getSharedPreferences("GetCodeService", Context.MODE_PRIVATE);
return shared.getString(pname,dvalue);
}
#Override
public boolean onStopJob(JobParameters params) {
return false;
}
private static class SendLocation extends AsyncTask<String, Void, String> {
MyService myService;
JobParameters jobParameters;
Context _context;
GPSTracker gps;
double lat,lon;
public SendLocation(MyService myService,JobParameters jobParameters,Context context){
this._context=context;
gps=new GPSTracker(context);
if (gps.canGetLocation){
lat=gps.getLatitude();
lon=gps.getLongitude();
}
this.myService=myService;
this.jobParameters=jobParameters;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String link = Config.IP_Config + "Hatef/getlocation.php";
HttpClient httpclint = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
try {
JSONObject jsonobj = new JSONObject();
jsonobj.put("latitude", lat+"");
jsonobj.put("longitude", lon+"");
jsonobj.put("code", strings[0]);
List<NameValuePair> namevaluepair = new ArrayList<NameValuePair>();
namevaluepair.add(new BasicNameValuePair("req", jsonobj.toString()));
httppost.setEntity(new UrlEncodedFormEntity(namevaluepair, HTTP.UTF_8));
HttpResponse response = httpclint.execute(httppost);
InputStream inputstream = response.getEntity().getContent();
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(inputstream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
myService.jobFinished(jobParameters, false);
}
}
}
Run Service
JobInfo.Builder builder=new JobInfo.Builder(100,new ComponentName(this,MyService.class));
builder.setPeriodic(10000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true);
mJobScheduler.schedule(builder.build());
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher2"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".second_page"
android:screenOrientation="portrait" >
</activity>
<service android:name=".MyService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"
/>
</application>

Service not Starting from AsyncTask

I tried to start my service from AsyncTask but cannot see that its starting.
Hope you can see my errors.
here my code:
protected String doInBackground(String... params) {
//starts service number activite
Intent i = new Intent(context, DownloadService.class);
i.putExtra("url", "www.google.com");
i.putExtra("receiver", new DownloadReceiver(new Handler()));
context.startService(i);
here is my service
public class DownloadService extends Service{
protected void onHandleIntent(Intent intent) {
String urlLink = intent.getStringExtra("url");
ResultReceiver receiver = intent.getParcelableExtra("receiver");
// some body
Bundle data = new Bundle();
//publishing progress
data.putString("key",getActivityUrl() );
receiver.send(1,data);
}
ResultReceiver resultReceiver;
public int onStart(Intent intent, int flags, int startId) {
onHandleIntent( intent)
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public String getActivityUrl() {.....}
and my manifest file:
<service android:name="connection.DownloadService">
<intent-filter>
<action android:name="connection.DownloadService">
</action>
</intent-filter>

Why am I getting a null pointer exception?

The title of this problem describes my problem. I have tried fixing this for a while and i am tired of searching and would like some help please. It used to work until I added the Handler and runner. I am trying to make an application that is a simple clock application that the user can set to any time that they want to. Whenever I go to run the application, it opens and then says it would not start properly. This is an activity that is set by another activity and then it changes the values it receives, it also displays these values in textviews.
package CoopFun.Clocks;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;
import android.content.Intent;
import android.app.Activity;
public class ClockMain extends Activity {
int Hours;
int Minutes;
int Seconds;
String TimeOfDayS;
TextView HoursMainV;
TextView MinutesMainV;
TextView SecondsMainV;
TextView TimeOfDayMainV;
Timer oneSecond;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.clock_main);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
int Hour = extras.getInt("HoursS");
Hour = Hours;
int Minute = extras.getInt("MinutesS");
Minute = Minutes;
int Second = extras.getInt("SecondsS");
Second = Seconds;
String TimeOfDaySs = extras.getString("TimeOfDayS");
TimeOfDaySs = TimeOfDayS;
HoursMainV = (TextView) findViewById(R.id.HoursMainV);
HoursMainV.setText(""+Hour);
MinutesMainV = (TextView) findViewById(R.id.MinutesMainV);
MinutesMainV.setText(":"+Minute);
SecondsMainV = (TextView) findViewById(R.id.SecondsMainV);
SecondsMainV.setText(":"+Second);
TimeOfDayMainV = (TextView) findViewById(R.id.TimeOfDayMainV);
TimeOfDayMainV.setText(" "+TimeOfDaySs);
final Handler handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
++Seconds;
if(Seconds == 60){
++Minutes;
Seconds = 0;
if(Minutes == 60) {
++Hours;
Minutes = 0;
if(Hours == 12){
if(TimeOfDayS.equals("AM")) {
TimeOfDayS = "PM";
} else{
TimeOfDayS = "AM";
}
Hours = 0;
}
}
}
HoursMainV.append(""+Hours);
if(Minutes <=9) {
MinutesMainV.append(":0"+Minutes);
} else {
MinutesMainV.append(":"+Minutes);
}
if(Seconds <=9) {
SecondsMainV.append(":0"+Seconds);
} else {
SecondsMainV.append(":"+Seconds);
}
TimeOfDayMainV.append(" " + TimeOfDayS);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:textSize="50dip"
android:id="#+id/HoursMainV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dip"></TextView>
<TextView
android:textSize="50dip"
android:id="#+id/MinutesMainV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView
android:textSize="50dip"
android:id="#+id/SecondsMainV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView
android:textSize="50dip"
android:id="#+id/TimeOfDayMainV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="CoopFun.Clocks"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Clock"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ClockMain">
</activity>
</application>
</manifest>
Thank you.
int Hour = extras.getInt("HoursS");
Hour = Hours;
int Minute = extras.getInt("MinutesS");
Minute = Minutes;
int Second = extras.getInt("SecondsS");
Second = Seconds;
String TimeOfDaySs = extras.getString("TimeOfDayS");
TimeOfDaySs = TimeOfDayS;
Change above code with this::
int Hour = extras.getInt("HoursS");
Hours = Hour;
int Minute = extras.getInt("MinutesS");
Minutes = Minute;
int Second = extras.getInt("SecondsS");
Seconds = Second;
String TimeOfDaySs = extras.getString("TimeOfDayS");
TimeOfDayS = TimeOfDaySs;
Simply, u were getting null pointer exception bcoz u were setting null values to Hour,Minute,Second and TimeOfDaySs and accessing them.
Cheers....!!!