I am trying to start up an android app as background service after initial run. At first run, the app should start as normal android app, then after, that it should be a background service which still runs even after booting. I wrote the following code. The service class is verified as standalone android app. But this app is not running as expected. No error code, but when debug, service class is not working.
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tulga.nar.mytrack">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<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"
android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Initial one time running activity class:
package com.tulga.nar.mytrack;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
}
public void starterHandler(View v)
{
new MyBroadcastReceiver();
}
}
Initial one time running activity class's xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tulga.nar.mytrack.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/starter"
android:text="start service"
android:onClick="starterHandler"/>
</android.support.constraint.ConstraintLayout>
Broadcast receiver class. It is called from MainActivity after start service button is clicked. It is supposed to start background MyService class.
package com.tulga.nar.mytrack;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context aContext, Intent aIntent) {
// This is where you start your service
aContext.startService(new Intent(aContext, MyService.class));
}
}
This is background MyService class. The class is verified and works as standalone app. But here, code execution is not reaching to here when debug.
package com.tulga.nar.mytrack;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Home on 8/27/2017.
*/
public class MyService extends AppCompatActivity implements
LocationListener
{
private class SendDeviceDetails extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String data = "";
HttpURLConnection connection = null;
try {
URL url=new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type",
"application/json");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
DataOutputStream wr = new
DataOutputStream(connection.getOutputStream());
wr.writeBytes(params[1]);
wr.flush();
wr.close();
InputStream in = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
} //catch (Exception e) {
//e.printStackTrace();
//}
catch (MalformedURLException e) {
e.printStackTrace();}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (connection != null) {
connection.disconnect();
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("TAG", result); // this is expecting a response code to be
sent from your server upon receiving the POST data
}
}
public static final int RequestPermissionCode = 1 ;
static public double myLong=151;
static public double myLat=-34;
static public String _id=null;
static public String _rev=null;
Button buttonEnable, buttonGet ;
TextView textViewLongitude, textViewLatitude ;
Context context;
Intent intent1 ;
Location location;
LocationManager locationManager ;
boolean GpsStatus = false ;
Criteria criteria ;
String Holder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
EnableRuntimePermission();
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
Holder = locationManager.getBestProvider(criteria, false);
context = getApplicationContext();
CheckGpsStatus();
JSONObject postData = new JSONObject();
try {
postData.put("_id",String.valueOf("9876543210"));
postData.put("Lat",
String.valueOf(String.valueOf(MyService.myLat)));
postData.put("Long",
String.valueOf(String.valueOf(MyService.myLong)));
postData.put("_rev",String.valueOf("1-
62076042d87cacd2711268d4a396129b"));
new SendDeviceDetails().execute("my-server-name/mydatabase",
postData.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
textViewLongitude.setText("Longitude:" + location.getLongitude());
textViewLatitude.setText("Latitude:" + location.getLatitude());
myLong=location.getLongitude();
myLat=location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
public void CheckGpsStatus(){
locationManager =
(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
GpsStatus =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(MyService.this,
Manifest.permission.ACCESS_FINE_LOCATION))
{
Toast.makeText(MyService.this,"ACCESS_FINE_LOCATION permission
allows us to Access GPS in app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MyService.this,new String[]{
Manifest.permission.ACCESS_FINE_LOCATION},
RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult)
{
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] ==
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MyService.this,"Permission Granted, Now your
application can access GPS.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MyService.this,"Permission Canceled, Now your
application cannot access GPS.", Toast.LENGTH_LONG).show();
}
break;
}
}
You didn't regest your serice in mainifest,and your broadcastReceiver is not at the right place.It should like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tulga.nar.mytrack">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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" android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".service.MyService">
<intent-filter>
<action android:name="write your action name" />
</intent-filter>
</service>
</application>
</manifest>
Related
I was creating an application to test whether File.listFiles() method is working or not. To check this I made an application and I used it there but this returning null in place of an array. This is my full code please help and I have granted all permissions for android 11
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.myapplication">
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
tools:node="merge" />
<uses-permission
android:name="android.permission.STORAGE"
tools:node="merge" />
<uses-permission
android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:requestLegacyExternalStorage="true"
android:theme="#style/Theme.MyApplication">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class MainActivity extends AppCompatActivity {
private Button deleteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
deleteButton = findViewById(R.id.deleteButton);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteFiles(view);
}
});
}
private void deleteFiles(View v) {
File file = new File("/storage/emulated/0/DCIM/");
if (file.isDirectory())
{
File[] files;
files = file.listFiles();
int a = files.length;
for (int i = 0; i < files.length; i++)
{
new File(file, files[i].getName()).delete();
}
Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), (CharSequence) file, Toast.LENGTH_LONG).show();
}
}
}
My app to access a simple JSON and display it runs perfectly fine on the emulator(PIXEL 2 API 24) but not on any actual device I connect to it. Tried with both S8 and Note10, neither have data saver on either.
I even checked the apps data use afterwards and it said "0 B".
Here are the files:
MainActivity.java:
package com.example.internettest;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JsonTask().execute("http://46d30cf268b0.ngrok.io/LEATest/");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
//pd = new ProgressDialog(MainActivity.this);
//pd.setMessage("Please wait");
//pd.setCancelable(false);
//pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//if (pd.isShowing()){
// pd.dismiss();
//}
Toast toast = Toast.makeText(getApplicationContext(),
"Before Try = |" + result + "|",
Toast.LENGTH_SHORT);
toast.show();
textView.setText(result);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.internettest">
<uses-permission android:name="android.permission.INTERNET" />
<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>
Here's the result of pressing the button on the emulator(all fake username/passwords):
Execure your JsonTask as follows -
new JsonTask().execute("https://46d30cf268b0.ngrok.io/LEATest/");
As suggested by #isthemartin, when you are running you app in actual device (S8 and Note10) the traffic is getting block because HTTP connection is not allowed.
Either you can add android:usesCleartextTraffic="true" but then you app will allow non secure HTTP connections.
I tried your API URL (https://46d30cf268b0.ngrok.io/LEATest/) is responding to the request so, why don't simply use it without making a security gap in your app.
probably your actual devices are blocking http connections, so in this case you need to enable those connections, check this post
Please add this code to your AndroidManifest.xml file.
android:usesCleartextTraffic="true"
so the code can be like this :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.internettest">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="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>
I would like to get the location of corporate devices using a corporate application.
I've had success with locating the device when the application is in foreground but doesn't seem to work when the app is in the background or killed.
I tried to use push notification to start a service or broadcastReceiver when the app is closed or in background but nothing works.
Is there a way to fetch the location of a device no matter what state the app is in?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.c7lab.fotodinamico">
<!--
io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here.
-->
<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.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="io.flutter.app.FlutterApplication"
android:icon="#mipmap/ic_launcher"
android:label="Corporate Application">
<receiver android:name=".MyLocationService"></receiver>
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name="com.example.crm_agenti.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
MyLocationService.class
package com.c7lab.fotodinamico;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.util.Log;
import com.google.android.gms.location.LocationResult;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import static android.content.Context.MODE_PRIVATE;
public class MyLocationService extends BroadcastReceiver {
public static final String ACTION_PROCESS_UPDATE = "com.c7lab.fotodinamico.UPDATE_LOCATION";
private static final String TAG = "MyLocationService";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "MYSERVICE WORK?");
SharedPreferences prefs = context.getSharedPreferences("FlutterSharedPreferences", MODE_PRIVATE);
String shared = prefs.getString("flutter.jsonData", null);
JsonObject ed = new JsonObject();
Gson g = new Gson();
if(shared != null) {
ed = new JsonParser().parse(shared).getAsJsonObject();
}
String usr = "no-usr";
if(ed.get("usr") != null) {
usr = ed.get("usr").getAsString();
}
if(intent != null) {
final String action = intent.getAction();
if(ACTION_PROCESS_UPDATE.equals(action)) {
LocationResult result = LocationResult.extractResult(intent);
if(result != null) {
Location location = result.getLastLocation();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String location_string = new StringBuilder(""+latitude).append(" - ").append(longitude).toString();
Log.v(TAG,location_string);
}
}
}
}
}
MainActivity.class
package com.c7lab.fotodinamico;
import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
private static final String TAG = "MainActivity";
private Handler mainHandler = new Handler();
static MainActivity instance;
LocationRequest locationRequest;
FusedLocationProviderClient fusedLocationProviderClient;
public static MainActivity getInstance() {
return instance;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
//scheduleJob();
getWindow().addFlags(LayoutParams.FLAG_SECURE);
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
updateLocation();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(MainActivity.this, "Accetta permessi posizione.", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
}
}).check();
}
#Override
protected void onStop() {
// call the superclass method first
super.onStop();
}
private void updateLocation() {
buildLocationRequest();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, getPendingIntent());
}
private PendingIntent getPendingIntent() {
Intent intent = new Intent(this, com.c7lab.fotodinamico.MyLocationService.class);
intent.setAction(com.c7lab.fotodinamico.MyLocationService.ACTION_PROCESS_UPDATE);
return PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
}
private void buildLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(3000);
locationRequest.setSmallestDisplacement(10f);
}
}
I have tried multiple solutions written on this site!
A lot of issues.
1)Don't use getLastLocation. This only works if the device already knows the location. Instead, use requestSingleUpdate to actually turn on the location hardware. This required you to use a real service, as a BroadcastReceiver would be killed too quickly. The BR can start the service though.
2)You need a foreground service, not a background service.
3)IN modern android, the user can choose to grant location only when the app is open and block all background access. Possibly a device policy owner can override this, not sure. But if it can't, you're screwed.
Probably it is just a silly mistake but i am having a Instantiate activity message when i tried to run my second activity
My first activity :
package com.burak.algonder;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b= (Button) findViewById(R.id.but2);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast toast = Toast.makeText(getBaseContext(), "opucuk!", Toast.LENGTH_LONG);
toast.show();
startActivity(new Intent(MainActivity.this, Pozsyon.class));
}
});
}
}
My second Activity:
package com.burak.algonder;
import java.util.List;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
public class Pozsyon extends Service implements LocationListener {
private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(
Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
My Android Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.burak.algonder"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.burak.algonder.MainActivity"
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="com.burak.algonder.Pozsyon" >
<intent-filter>
<action android:name="android.intent.action.Pozsyon" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<receiver android:name="com.burak.algonder.SmsReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
Thank you for your help.
Pozsyon Class is not Activity and can't be started here!
I started to learn Android a few days ago, and I'm stuck developing this app, what it does is basically connect to an API using volley, but when I try to run the app in my smartphone I get the following error:
-25 10:17:46.851 24476-24476/com.representemais E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.rep, PID: 24476
java.lang.NullPointerException
at com.rep.app.principal.InicioActivity$AutenticacaoLocalTask$1.onResponse(InicioActivity.java:89)
at com.representemais.app.principal.InicioActivity$AutenticacaoLocalTask$1.onResponse(InicioActivity.java:84)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
This is the InicioActivity:
package com.rep.app.principal;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.rep.R;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class InicioActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AutenticacaoLocalTask mAutenticacaoLocalTask = new AutenticacaoLocalTask();
mAutenticacaoLocalTask.execute((Void) null);
}
private TextView txtDisplay;
RequestQueue queue = Volley.newRequestQueue(this);
public class AutenticacaoLocalTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
String url = "http://192.168.1.15/rep-api/api/clients";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
txtDisplay.setText("Response => "+response.toString());
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-API-TOKEN", "99KI9Gj68CgCf70deM22Ka64chef2C40Gm2lFJ2J0G9JkD0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8");
return headers;
}
};
queue.add(jsonObjReq);
return true;
} catch (Exception e) {
Log.e("RM", e.getMessage());
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
}
#Override
protected void onCancelled() {
}
}
And the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rep"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".app.principal.InicioActivity"
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=".app.login.LoginActivity"
android:configChanges="keyboardHidden"
android:label="#string/app_name">
</activity>
<activity
android:name=".app.principal.MainActivity"
android:label="#string/app_name"></activity>
<activity android:name=".app.cliente.ClienteDetalheActivity"
android:label="#string/app_name"></activity>
<activity android:name=".app.login.LoginTelaBloqueada"
android:label="#string/app_name"></activity>
</application>
</manifest>
I think your forget to
setContentView(R.layout.your_layout);
You should set layout in your onCreate(...) method and then reference TextView.
Correct:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
.........
........
}
At a quick glance, it looks like you aren't setting the content view, which would cause findViewById to return null. Attempting to set the text in the non-existing TextView is what seems to be the direct cause of the crash.