Android AIDL iBinder NullPointerException - android

Purpose: use AIDL to communicate two app (one is called service ,one is called client)
Condition: IDE: Android Studio ,In service ,I define a IPerson.aidl (in this file I define a interface called queryPerson )which AS will generate the IPerson.java in GENERATED dir . I also add IntentFilter(action ,category) AndroidMainfest.xml in main And I create a AIDLService to extends the IPerson.Stub and implement the interface queryPerson . After that I make another app called client to communicate with service But got NOPOINTER Exception
here are code in service:
IPerson.aidl:
// IPerson.aidl
package com.example.jason.aidldemo;
// Declare any non-default types here with import statements
interface IPerson {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
String queryPerson(int num);
}
AIDLService.java:
package com.example.jason.aidldemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class AIDLService extends Service {
private IBinder iBinder=new PersonQueryBinder();
private String [] names={"Apple","Banana","peach"};
private String query(int num)
{
if(num>0 && num<4)
{
return names[num-1];
}
return null;
}
public AIDLService() {
}
private final class PersonQueryBinder extends IPerson.Stub
{
#Override
public String queryPerson(int num) throws RemoteException {
return query(num);
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
}
AndroidMainfest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jason.aidldemo" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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>
<service
android:name=".AIDLService"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.AIDLService"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
</application>
</manifest>
In client:
activity-main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:id="#+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edit_num"
android:layout_below="#+id/textView"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Query"
android:id="#+id/btn_query"
android:layout_below="#+id/edit_num"
android:layout_alignParentStart="true"
android:layout_marginTop="26dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tx_name"
android:layout_marginTop="20dp"
android:layout_below="#+id/btn_query" />
</RelativeLayout>
MainActivity.java:
package com.example.jason.aidlclient;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.jason.aidldemo.IPerson;
public class MainActivity extends Activity implements View.OnClickListener {
private IPerson iPerson;
private Button btn_query;
private TextView tx_name;
private EditText edit_name;
private PersonConnection pconn=new PersonConnection();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindView();
//bind remoted service
Intent service=new Intent("android.intent.action.AIDLService");
service.setPackage("com.example.jason.aidldemo");
bindService(service,pconn,BIND_AUTO_CREATE);
}
private void bindView()
{
edit_name= (EditText) findViewById(R.id.edit_num);
btn_query= (Button) findViewById(R.id.btn_query);
tx_name= (TextView) findViewById(R.id.tx_name);
btn_query.setOnClickListener(this);
}
/**
* Called when a view has been clicked.
*
* #param v The view that was clicked.
*/
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.btn_query:
String number=edit_name.getText().toString();
int num=Integer.valueOf(number);
try{
String temp=iPerson.queryPerson(num);
tx_name.setText(temp);
} catch (RemoteException e) {
e.printStackTrace();
}
edit_name.setText("");
break;
}
}
private final class PersonConnection implements ServiceConnection{
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
iPerson= (IPerson.Stub) IPerson.Stub.asInterface(service);
}
#Override
public void onServiceDisconnected(ComponentName name) {
iPerson=null;
}
}
}
And I want Demo to run like this :
enter image description here
But got problem NOPOINTER
Hope someone teach ME!! THANKS!!

Your service is returning a null binder. You have to return the AIDL interface stub like this:
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new IPerson.Stub(){
#Override
public String queryPerson(int num) throws RemoteException {
return query(num);
}
}
}

Related

Android SharedPreferences not removed until app is restarted

I'm stucked with this problem.
In my app I use SharedPrefManager as a singleton class, in order to keep some "session" information. In this simple example app I just save the user's name and a boolean that indicates whether or not the user is logged in to skip the login screen if already logged, or to show it if not.
When starting the app, after the splashscreen, the LoginActivity is started.
At this point, if the user has already logged in before (without logging out later, that means the boolean value of isuseradded SharedPreferences variable is true), the user is redirected to the MainActivity, otherwise he sees the login form, where he can insert username and password and make a REST API request to a remote server.
If the login is correct, the MainActivity starts and simply shows the name of the user, taken from the response JSON obtained by the remote login REST API call.
Now, here is my problem: I want to implement a simple logout feature that deletes (or changes, as in this test app) all the information stored by SharedPreferences and takes the user back to the LoginActivity.
But when I click logout, the values for SharedPreferences are updated only in MainActivity, while in LoginActivity they remain the same as before, so when the user is redirected to LoginActivity, the isusedadded shared preference is still true, and the user is redirected back to MainActivity.
But SharedPrefManager class is a singleton, so its values should be the same in every part of the app, because only one instance of it exists, so why do I have this behavior?
You can test the app by downloading the full app code here and using these credentials for login:
Username: 52346
Password: 32fjueM1 (case sensitive)
Here follows my code.
App.java:
package mypackage.sharedprefapp;
import android.app.Application;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class App extends Application
{
private RequestQueue mRequestQueue;
private static App mInstance;
#Override
public void onCreate()
{
super.onCreate();
mInstance = this;
}
public static synchronized App getInstance()
{
return mInstance;
}
// This method returns the queue containing GET/POST requests
public RequestQueue getRequestQueue()
{
if(mRequestQueue == null)
{
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
// This method adds a GET/POST request to the queue of requests
public <T> void addToRequestQueue(Request<T> req)
{
getRequestQueue().add(req);
}
}
SplashActivity.java
package mypackage.sharedprefapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class SplashActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
LoginActivity.java
package mypackage.sharedprefapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class LoginActivity extends AppCompatActivity
{
private static final String TAG = "LoginActivity";
Button loginButton;
EditText userIDInput, passwordInput;
TextView loginErrorMsg, title;
LinearLayout bgLayout;
SharedPrefManager sharedPrefManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPrefManager = SharedPrefManager.getInstance(this);
Log.i("HERE", "LoginActivity onCreate: "+sharedPrefManager.isUserAdded());
}
#Override
protected void onResume()
{
super.onResume();
sharedPrefManager = SharedPrefManager.getInstance(this);
Log.i("HERE", "LoginActivity onResume: "+sharedPrefManager.getUserName());
// if the user is already logged in
if(sharedPrefManager.isUserAdded())
{
Log.i(TAG, "User is logged in");
// if the device is connected to the internet
if(Utils.isDeviceOnline(this))
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
// if the device is offline
else
{
Log.i(TAG, "Internet connection is not available");
}
}
// if the user is not logged in
else
{
Log.i(TAG, "User is NOT logged in");
setContentView(R.layout.activity_login);
title = (TextView) findViewById(R.id.title);
loginErrorMsg = (TextView) findViewById(R.id.login_errorText);
userIDInput = (EditText) findViewById(R.id.login_id_paziente);
passwordInput = (EditText) findViewById(R.id.login_password);
loginButton = (Button) findViewById(R.id.login_submitButton);
bgLayout = (LinearLayout) findViewById(R.id.login_parentLayout);
// Bind a custom click listener to the login button
loginButton.setOnClickListener(new LoginButtonClickListener(this));
// Bind a custom click listener to the background layout
// so that the soft keyboard is dismissed when clicking on the background
bgLayout.setOnClickListener(new LoginBackgroundClickListener());
}
}
}
LoginButtonClickListener.java
package mypackage.sharedprefapp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginButtonClickListener implements View.OnClickListener
{
private Context context;
private SharedPrefManager sharedPrefManager;
public LoginButtonClickListener(Context c)
{
this.context = c;
}
#Override
public void onClick(View v)
{
sharedPrefManager = SharedPrefManager.getInstance(context);
// if internet connection is available
if(Utils.isDeviceOnline(context))
{
// Verify login credentials from DB
doLogin();
}
else {}
}
// check login data with REST API
private void doLogin()
{
final String paziente_id = ((EditText)((Activity)context).findViewById(R.id.login_id_paziente)).getText().toString();
final String paziente_password = ((EditText)((Activity)context).findViewById(R.id.login_password)).getText().toString();
StringRequest stringRequest = new StringRequest
(
Request.Method.POST,
"http://www.stefanopace.net/iCAREServer/api/v1/index.php/login",
new Response.Listener<String>()
{
#Override
public void onResponse(String s)
{
try
{
JSONObject obj = new JSONObject(s);
if(!obj.getBoolean("error"))
{
String name = obj.getString("nome");
sharedPrefManager.addUser(name);
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
}
else
{
Toast.makeText(context, "Error on JSON response", Toast.LENGTH_LONG).show();
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError volleyError)
{
Toast.makeText(context, volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("id_paziente", paziente_id);
params.put("password", paziente_password);
return params;
}
};
App.getInstance().addToRequestQueue(stringRequest);
}
}
LoginBackgroundClickListener.java
package mypackage.sharedprefapp;
import android.view.View;
public class LoginBackgroundClickListener implements View.OnClickListener
{
#Override
public void onClick(View v)
{
Utils.hideSoftKeyboard(v);
}
}
MainActivity.java
package mypackage.sharedprefapp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
private static final String TAG = "MainActivity";
TextView personName;
SharedPrefManager sharedPrefManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPrefManager = SharedPrefManager.getInstance(this);
setContentView(R.layout.activity_main);
personName = (TextView) findViewById(R.id.person_name);
Log.i(TAG, "Value: "+sharedPrefManager.isUserAdded());
personName.setText(sharedPrefManager.getUserName());
}
#Override
protected void onResume()
{
super.onResume();
sharedPrefManager = SharedPrefManager.getInstance(this);
Log.w("MainActivity", "onResume");
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
// Logout button has been pressed
case R.id.logout_action:
{
Log.i("Logout pressed", "Logout button has been pressed!");
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton
(
"Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
boolean success = sharedPrefManager.removeDataFromSharedPreference();
// if the operation is OK
if(success)
{
// go to the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Error during logout", Toast.LENGTH_LONG).show();
}
}
}
);
alertDialogBuilder.setNegativeButton
(
"No",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{}
}
);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
}
return super.onOptionsItemSelected(item);
}
}
SharedPrefManager.java
package mypackage.sharedprefapp;
import android.content.Context;
import android.content.SharedPreferences;
public final class SharedPrefManager
{
private static final String TAG = "SharedPrefManager";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private static SharedPrefManager mInstance;
private static final String SHARED_PREF = "sharedprefs";
private static final String KEY_IS_USER_ADDED = "isuseradded";
public static final String KEY_USER_NAME = "username";
private SharedPrefManager(Context context)
{
sharedPreferences = context.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
sharedPreferences.registerOnSharedPreferenceChangeListener(new LocalSharedPreferencesChangeListener());
}
public static SharedPrefManager getInstance(Context context)
{
if(mInstance == null)
{
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
// add an user to the shared preferences
public boolean addUser(String name)
{
editor.putString(KEY_USER_NAME, name);
editor.putBoolean(KEY_IS_USER_ADDED, true);
return editor.commit();
}
public boolean removeDataFromSharedPreference()
{
editor.putString(KEY_USER_NAME, "HELLO");
editor.putBoolean(KEY_IS_USER_ADDED, false);
return editor.commit();
}
public String getUserName()
{
return sharedPreferences.getString(KEY_USER_NAME, "");
}
public boolean isUserAdded()
{
return sharedPreferences.getBoolean(KEY_IS_USER_ADDED, false);
}
}
Utils.java
package mypackage.sharedprefapp;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class Utils
{
public static void hideSoftKeyboard(View view)
{
InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
// This method checks if the device is connected to the Internet
public static boolean isDeviceOnline(final Context context)
{
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager != null)
{
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
boolean isOnline = (networkInfo != null && networkInfo.isConnectedOrConnecting());
if(!isOnline)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setCancelable(false);
alertDialog.setTitle("Error");
alertDialog.setMessage("Internet is not available");
alertDialog.setPositiveButton("Try again", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Reload the Activity
Intent intent = ((Activity) context).getIntent();
((Activity) context).finish();
context.startActivity(intent);
}
});
alertDialog.show();
}
return isOnline;
}
return false;
}
}
LocalSharedPreferencesChangeListener
package mypackage.sharedprefapp;
import android.content.SharedPreferences;
import android.util.Log;
public class LocalSharedPreferencesChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener
{
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
Log.i("HERE", key);
}
}
activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".LoginActivity"
android:padding="0dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
android:layout_gravity="center_horizontal">
<LinearLayout
android:id="#+id/login_parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:clickable="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:layout_marginBottom="30dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:layout_marginBottom="30dp"
android:singleLine="false"
android:padding="5dp"
android:textSize="30sp" />
<EditText
android:id="#+id/login_id_paziente"
android:layout_width="match_parent"
android:layout_height="40dp"
android:inputType="number"
android:ems="10"
android:hint="Username"
android:textColor="#android:color/black"
android:textColorHint="#android:color/darker_gray"
android:singleLine="true"
android:minLines="1"
android:gravity="center_horizontal"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:focusableInTouchMode="true"
android:focusable="true" />
<EditText
android:id="#+id/login_password"
android:layout_width="match_parent"
android:layout_height="40dp"
android:hint="Password"
android:textColorHint="#android:color/darker_gray"
android:inputType="textPassword"
android:ems="10"
android:textColor="#android:color/black"
android:maxLines="1"
android:singleLine="true"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:focusableInTouchMode="true"
android:focusable="true" />
<TextView
android:id="#+id/login_errorText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login error"
android:textColor="#android:color/holo_red_dark"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:singleLine="false"
android:padding="5dp"
android:textSize="20sp"
android:layout_margin="10dp"
android:visibility="invisible" />
<Button
android:id="#+id/login_submitButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:textSize="20sp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="mypackage.sharedprefapp.MainActivity">
<TextView
android:id="#+id/person_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="25sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
splashscreen.xml (in drawable resources folder)
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/holo_green_dark"/>
<item>
<bitmap
android:gravity="center"
android:src="#mipmap/ic_launcher"/>
</item>
</layer-list>
mainmenu.xml (in res/menu resource folder)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/logout_action"
android:title="Logout"
app:showAsAction="always" />
</menu>
styles.xml
<resources>
...
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">#drawable/splashscreen</item>
</style>
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mypackage.sharedprefapp">
<!-- Needs internet to connect to Google Services -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Permission to check internet connection state -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme" />
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:process=":other_process"
android:screenOrientation="portrait"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.LOGIN_ACTION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle (Module: app)
dependencies {
...
compile 'com.android.volley:volley:1.0.0'
}
Thank you!
Just call editor.clear();
and editor.commit();
is enough to delete all data from shared preference.
Because onResume, you keep on instantiating a new SharedPrefManager
sharedPrefManager = new SharedPrefManager(this);
Modify your SharedPrefManager so that it only gives one instance at all times OR make sure that you are referring to the same object when you return to LoginActivity.
SharedPreferences is permanent storage, you can clear
SharedPreferences.Editor.clear().commit();
alternate solution
you want once app close clear entire values,try Application singleton class
#Ciammarica you can call this code on click of Logout button, hope this can help you..you can set in logout button boolean value false..
SessionManager.setUserLoggedIn(YourActivity.this, false); SessionManager.clearAppCredential(YourActivity.this);
I Changed my code in order to have only one instance of SharedPrefManager class.
This is my App singleton class:
public class App extends Application
{
private static App mInstance;
private SharedPrefManager sharedPrefManager;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
sharedPrefManager = new SharedPrefManager(this);
}
public SharedPrefManager getSharedPrefManager(){
return sharedPrefManager;
}
public static synchronized App getInstance(){
return mInstance;
}
}
Then from other classes I get the instance by calling
SharedPrefManager sharedPrefManager = App.getInstance().getSharedPrefManager();
Now, with this change, the onSharedPreferenceChanged() event is triggered only once, so this is better than before, but the "delayed" behavior is still there... I mean, even if I use editor.clear(); and editor.commit(); methods, the values are updated but I can see them only if I close and open the app again.
I found the problem myself... It didn't like the sharedPrefManager.removeDataFromSharedPreference(); method to be called from inside new DialogInterface.OnClickListener()
I took it in another part of the code and it worked.

Android app crashes on Bluetooth connect?

I'm trying to connect to other Android devices using Bluetooth via my app. The app works fine while discovering nearby Bluetooth devices. However, upon connecting, the app crashes.
I have two JAVA files other than MainActivity.java that are responsible for discovering & connecting to other Bluetooth devices. Their codes are posted below:
SearchBTDevice.java (for discovering nearby devices)
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattDescriptor;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Set;
public class SearchBTDevice extends AppCompatActivity {
public BluetoothAdapter BlueAdapter = BluetoothAdapter.getDefaultAdapter();
public ArrayAdapter PairedArrayAdapter;
public ArrayAdapter BTArrayAdapter;
BluetoothDevice btd;
public ListView devicesFound;
private final BroadcastReceiver BTReceiver= new BroadcastReceiver(){
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(btd.getName() + "\t" + btd.getAddress() + "\n");
}
}
};
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_FOUND);
#Override
protected void onResume() {
super.onResume();
this.registerReceiver(BTReceiver,filter1);
}
#Override
protected void onPause() {
super.onPause();
BlueAdapter.cancelDiscovery();
this.unregisterReceiver(BTReceiver);
Toast.makeText(SearchBTDevice.this, "Discovery Stopped!!", Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
searchBTDevices();
}
public void searchBTDevices()
{
if(!BlueAdapter.startDiscovery())
Toast.makeText(SearchBTDevice.this, "Failed to Start Discovery", Toast.LENGTH_SHORT).show();
else
Toast.makeText(SearchBTDevice.this, "Discovery Startred", Toast.LENGTH_SHORT).show();
BTArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
devicesFound = (ListView)findViewById(R.id.searchpagelistView);
devicesFound.setAdapter(BTArrayAdapter);
devicesFound.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent connectedBTintent = new Intent(SearchBTDevice.this, ConnectedBTDevice.class);
connectedBTintent.putExtra("BluetoothDevice", btd);
startActivity(connectedBTintent);
}
});
}
}
This is updated ConnectedBTDevice.java, responsible for connecting devices
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.IOException;
import java.util.UUID;
public class ConnectedBTDevice extends AppCompatActivity {
public BluetoothDevice btd;
public BluetoothSocket btSocket, tempSocket;
private UUID myUUID;
ArrayAdapter arr;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connected_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
arr = new ArrayAdapter(this, android.R.layout.simple_list_item_2);
btd = getIntent().getParcelableExtra("BluetoothDevice");
connectBT();
displayStuff();
}
public void connectBT() {
Thread myThread = new Thread() {
public void run() {
tempSocket = null;
try {
tempSocket = btd.createRfcommSocketToServiceRecord(myUUID);
} catch (IOException e) {
e.printStackTrace();
}
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
try {
tempSocket.connect();
arr.add("CONNECTED TO-->" + btd.getName());
} catch (IOException e) {
e.printStackTrace();
try {
tempSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
};
myThread.start();
}
public void displayStuff()
{
lv = (ListView)findViewById(R.id.connectedBTlistView);
lv.setAdapter(arr);
}
}
This is activity_connected_btdevice.xml for ConnectedBTDevice.java activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context="vertex2016.mvjce.edu.bluealert.SearchBTDevice">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.NoActionBar.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.NoActionBar.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_connected_btdevice" />
</android.support.design.widget.CoordinatorLayout>
This is content_connected_btdevice.xml for ConnectedBTDevice.java
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="vertex2016.mvjce.edu.bluealert.ConnectedBTDevice"
tools:showIn="#layout/activity_connected_btdevice">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/connectedBTimageView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:src="#drawable/bluealert_bg"
android:scaleType="centerCrop"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Connected Bluetooth Device"
android:id="#+id/connectedBTtextextView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="105dp"
android:textSize="25dp"
android:textAlignment="center"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/connectedBTlistView"
android:layout_below="#+id/connectedBTtextextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp" />
</RelativeLayout>
This is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="vertex2016.mvjce.edu.bluealert">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="#mipmap/bluealerticon"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar">
<activity
android:name=".SplashScreen"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" />
<activity
android:name=".SearchBTDevice"
android:label="#string/title_activity_search_btdevice"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="vertex2016.mvjce.edu.bluealert.MainActivity" />
</activity>
<activity
android:name=".ConnectedBTDevice"
android:label="#string/title_activity_connected_btdevice"
android:parentActivityName=".SearchBTDevice"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="vertex2016.mvjce.edu.bluealert.SearchBTDevice" />
</activity>
</application>
</manifest>
Here's the exception that my updated logcat shows
03-24 00:19:40.541 7205-9703/vertex2016.mvjce.edu.bluealert E/AndroidRuntime: FATAL EXCEPTION: Thread-35890
Process: vertex2016.mvjce.edu.bluealert, PID: 7205
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.UUID.getMostSignificantBits()' on a null object reference
at android.os.ParcelUuid.writeToParcel(ParcelUuid.java:129)
at android.bluetooth.IBluetooth$Stub$Proxy.connectSocket(IBluetooth.java:1767)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:309)
at vertex2016.mvjce.edu.bluealert.ConnectedBTDevice$1.run(ConnectedBTDevice.java:63)
I don't understand what the problem is. I have tried several online tutorials, but nothing seemed to work. I know the problem is in my ConnectedBTDevice.java, but can't figure out the point at which it's throwing the exception.
Thank you for your time.
You are assigning BluetoothSocket to tempSocket, and then you try to invoke connect() method on btSocket which is null.

Android service error Attempt to invoke virtual method

I am making an app, where a server in java sends a Place Array and other stuff in other activities. so I create a service to connect to the server from different activities. I have not implement server connection yet but I am simulating the server response, which I pass as parameter to an adapter (the adapter is tested), that I create to show this places in a ListView. so I got my Place array in my activity and I set it to the return object from a method in the service, but when I run the app it crashes and I got this error message:
java.lang.NullPointerException: Attempt to invoke virtual method
'com.remedialguns.smartourist.Place[]
com.remedialguns.smartourist.ConnectionService.getPlaces()' on a null
object.
UPDATE now is te same error but in myAdapter class when name.setText...
so this is my service.
package com.remedialguns.smartourist;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Locale;
public class ConnectionService extends Service {
Socket s;
PrintStream os;
private static final String TAG="com.remedialguns.smartourist";
private final IBinder myBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return myBinder;
}
public void sendProfileData(){
//send profile data to server
}
public Place[] getPlaces(){
Place[] PlacesToShow = new Place[10];
//F̶a̶k̶e̶ ̶d̶a̶t̶a̶ Test data
PlacesToShow[0]= new Place("MUSEO","Museo Nacional Agropecuario", 0.15, 0.4, 0.12);
PlacesToShow[1]= new Place("MUSEO","Museo Arqueológico Junín",0.10, 0.78, 0.44);
PlacesToShow[2]= new Place("MUSEO","Museo Botero", 0.2, 0.8, 0.08);
PlacesToShow[3]= new Place("MUSEO","Museo de Zea", 0.3, 0.65, 0.23);
PlacesToShow[4]= new Place("MUSEO","MUSEO DEL ORO", 0.13, 0.56, 0.12);
PlacesToShow[5]= new Place("MUSEO","MUSEO DE ARTE COLONIAL", 0.3, 0.67, 0.14);
PlacesToShow[6]= new Place("MUSEO","MUSEO HISTORICO DE LA POLICIA NACIONAL", 0.34, 0.3, 0.33);
PlacesToShow[8]= new Place("MUSEO","MUSEO DE LOS NIÑOS", 0.05, 0.65, 0.03);
PlacesToShow[7]= new Place("MUSEO","Museo Nacional", 0.15, 0.4, 0.12);
PlacesToShow[9]= new Place("MUSEO","MUSEO MILITAR", 0.07, 0.5, 0.6);
return PlacesToShow;
}
public class LocalBinder extends Binder {
ConnectionService getService(){
return ConnectionService.this;
}
}
}
this is my activity with my ListView and adapter.(UPDATE)
package com.remedialguns.smartourist;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.IBinder;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import com.remedialguns.smartourist.ConnectionService.LocalBinder;
import com.google.android.gms.location.places.Places;
public class ListActivity extends AppCompatActivity {
ConnectionService tcpService;
boolean isBound=false;
//Place[] PlacesToShow=tcpService.getPlaces();
Place[] PlacesToShow=new Place[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent i = new Intent(this, ConnectionService.class);
bindService(i, myConnection, Context.BIND_AUTO_CREATE);
// PlacesToShow=tcpService.getPlaces();
if (isBound) {
PlacesToShow = tcpService.getPlaces();
}
//Place[] PlacesToShow=tcpService.getPlaces();
ListAdapter MyAdapter = new MyAdapter(this, PlacesToShow);
ListView ListPlaces=(ListView) findViewById(R.id.MyList);
ListPlaces.setAdapter(MyAdapter);
ListPlaces.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Context context = view.getContext();
TextView textViewItem = ((TextView)view.findViewById(R.id.name));
String name =textViewItem.getText().toString();
TextView textViewItem2 = (TextView)findViewById(R.id.description);
String descripcion=textViewItem2.getText().toString();
Toast.makeText(context,"lugar: "+name+", descripcion: "+descripcion,Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private ServiceConnection myConnection=new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalBinder binder = (LocalBinder) service;
tcpService = binder.getService();
PlacesToShow = tcpService.getPlaces();
isBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
isBound=false;
}
};
}
this is my activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_list"
tools:context="com.remedialguns.smartourist.ListActivity">
<!-- <TextView
android:id="#+id/answer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="these are the places that our smart monkeys had find for you."/>
-->
<ListView
android:id="#+id/MyList"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
this is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.remedialguns.smartourist" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity
android:name=".RealMainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity
android:name=".ListActivity"
android:label="#string/app_name"
android:parentActivityName=".RealMainActivity"
android:theme="#style/AppTheme.NoActionBar" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.remedialguns.smartourist.RealMainActivity" />
</activity>
<service
android:name=".ConnectionService"
android:enabled="true"
android:exported="true" >
</service>
</application>
</manifest>
this is my adapter class
package com.remedialguns.smartourist;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<Place> {
MyAdapter(Context context, Place[] places){
super(context, R.layout.visual_place, places);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater MyInflater = LayoutInflater.from(getContext());
View placeView = MyInflater.inflate(R.layout.visual_place, parent, false);
Place singlePlaceItem=getItem(position);
TextView name=(TextView) placeView.findViewById(R.id.name);
ImageView icon =(ImageView) placeView.findViewById(R.id.icon);
TextView description = (TextView) placeView.findViewById(R.id.description);
name.setText(singlePlaceItem.getName().toString());
icon.setImageResource(R.mipmap.ic_launcher);
description.setText("Cost "+singlePlaceItem.getCost()+", distance "+singlePlaceItem.getDistance()+", rate "+singlePlaceItem.getRate()+" *");
return placeView;
}
}
please help me.
Here:
bindService(i, myConnection, Context.BIND_AUTO_CREATE);
Place[] PlacesToShow=new Place[10];
PlacesToShow=tcpService.getPlaces();
tcpService is null probably using is to call getPlaces() method before onServiceConnected method is called.
Use isBound to check onServiceConnected is called or not before using tcpService object:
if(isBound){
//
PlacesToShow=tcpService.getPlaces();
}
and also use onServiceConnected method as:
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalBinder binder = (LocalBinder) service;
tcpService = binder.getService();
PlacesToShow=tcpService.getPlaces();
isBound=true;
}
Also make sure added ConnectionService in AndroidManifest.xml as service.

Android Music Player Service not playing after home/back button is pressed

Am trying to write music player code in android.I wrote the MediaPlayer code in a service.Here is the code:
package com.example.audioservice;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
static MediaPlayer mp;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
System.out.println("in MyService onCreate()");
mp=MediaPlayer.create(getApplicationContext(),R.raw.subanallah);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
System.out.println("in onService onBind()");
return null;
}
#Override
public int onStartCommand(Intent intent,int flags, int startId) {
super.onStart(intent, startId);
Log.d("log", "In onStart.");
System.out.println("in MyService onStartCommand()");
mp.start();
return Service.START_STICKY;
}
}
and called the service from Activity
Intent s=new Intent(this,MyService.class);
startService(s);
Added the Service in manifest file
<service android:name="com.example.audioservice.MyService"></service>
But when home/backbutton is pressed app is restarting again.My requirement is when home/back button is pressed the app should continously play the music.Please help me.
Edited full code
Do this step by step ::
crate activity_main.xml and paste this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/playId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/stopId"
android:layout_marginRight="53dp"
android:text="Play" />
<Button
android:id="#+id/stopId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="48dp"
android:layout_marginTop="50dp"
android:text="Stop" />
After that create MyService class and paste this
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class MyService extends Service {
MediaPlayer mp;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate()
{
super.onCreate();
mp = MediaPlayer.create(getApplicationContext(), R.raw.ram3);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
mp.start();
mp.setLooping(true);
return 0;
}
#Override
public void onDestroy()
{
mp.release();
super.onDestroy();
}
}
After that create MainActivity1 class and paste this
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class MainActivity1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button play, stop;
play = (Button) findViewById(R.id.playId);
stop = (Button) findViewById(R.id.stopId);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent service = new Intent(MainActivity1.this, MyService.class);
startService(service);
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent name = new Intent(MainActivity1.this, MyService.class);
stopService(name);
}
});
}
}
Last step is paste the following code AndroidManifest.XML
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity1"
android:label="#string/app_name" >
<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" >
</service>
</application>
It's must work, no doubt about this.
Hope I can help you.
1.Use startForeground() (I haven't tried this way)
2.Put this code under startService(): bindService(Intent,ServiceConnection, BIND_IMPORTAN). Ofcourse, you need implement.(I use it and in my case that works).

"Unfortunately (my app) has Stopped" error when trying to run my application

(Home.java), I am trying to create a loading screen that eventually leads to this page (Home.java.)
package com.androidpeople.splash;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class VirtualSkiInstructor extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("Main Activity");
setContentView(textView);
}
}
Loading Screen (SplashScreen.java). This is the code that creates the Splash Screen, and the loading page
package com.androidpeople.splash;
import your.custom.splash.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class SplashScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
final int welcomeScreenDisplay = 3000;
/** create a thread to show splash up to splash time */
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
System.out.println("EXc=" + e);
} finally {
startActivity(new Intent(SplashScreen.this,
VirtualSkiInstructor.class));
finish();
}
}
};
welcomeThread.start();
}
}
(splash.xml)
<LinearLayout android:id="#+id/LinearLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center" android:background="#6B8AAD">
<TextView android:id="#+id/TextView01" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="18sp"
android:textStyle="bold" android:textColor="#fff"></TextView>
</LinearLayout>
(strings.xml)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Compass</string>
<string name="app_name">Compass</string>
</resources>
Add below code to add VirtualSkiInstructor activity into your manifest file.
<activity
android:name=".VirtualSkiInstructor"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Add VirtualSkiInstructor Activity in the AndroidManifest.xml file.
<activity android:name=".VirtualSkiInstructor"> </activity>

Categories

Resources