Service doesnt work correctly in Background - java

I am making Music Player which downloads music from Firebase.
Its working fine but I cannot play music in background.
It works for like 1.5 minute (after locking screen) and it stops.
In logs after I lock screen it says "Inactivity, disconnecting from Service".
I think this may be main problem here.
Here code :
Fragment of Playing Music:
public class PlayerFragment extends Fragment {
private FirebaseStorage storage;
private ImageButton main_btn, next_btn, back_btn, fav_btn, settings_btn;
private Uri localSong;
private Intent myService;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_player, container, false);
storage = FirebaseStorage.getInstance();
main_btn= view.findViewById(R.id.player_main_btn);
next_btn= view.findViewById(R.id.player_next_btn);
back_btn= view.findViewById(R.id.player_back_btn);
fav_btn = view.findViewById(R.id.player_song_fav_btn);
settings_btn = view.findViewById(R.id.player_song_options_btn);
storage.getReference().child("songs/ni_bien_ni_mal.mp3").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
localSong=uri;
}
});
MainActivity mainActivity = (MainActivity) getActivity();
myService = new Intent(getActivity(), BackgroundSoundService.class);
main_btn.setOnClickListener(v -> {
if( main_btn.getDrawable().getConstantState().equals( main_btn.getContext().getDrawable(R.drawable.ic_play).getConstantState()))
{
new Thread(new Runnable() {
#Override
public void run() {
myService.putExtra("uri",localSong.toString() );
mainActivity.startService(myService);
}
}).start();
main_btn.setImageResource(R.drawable.ic_pause);
}
else
{
new Thread(new Runnable() {
#Override
public void run() {
// mainActivity.stopService(myService);
main_btn.setImageResource(R.drawable.ic_play);
}
}).start();
}
});
fav_btn.setOnClickListener(v->{
if( fav_btn.getDrawable().getConstantState().equals( fav_btn.getContext().getDrawable(R.drawable.ic_heart_empty).getConstantState()))
{
fav_btn.setImageResource(R.drawable.ic_heart_full);
}else{
fav_btn.setImageResource(R.drawable.ic_heart_empty);
}
});
return view;
}
}
Manifest: ( Service declaration is at bottom)
<?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.company.altasnotas">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
<application
android:allowBackup="true"
android:icon="#drawable/altas_notes"
android:label="#string/app_name"
android:roundIcon="#drawable/altas_notes"
android:supportsRtl="true"
android:testOnly="false"
android:theme="#style/Theme.AltasNotas">
<activity
android:name=".IntroActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AltasNotas.NoActionBar"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"
tools:replace="android:value" />
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
</activity>
<service android:enabled="true" android:name=".BackgroundSoundService" />
</application>
</manifest>
Service :
public class BackgroundSoundService extends Service {
String song_string;
int x;
private static final String TAG = "BackgroundSoundService";
MediaPlayer player;
public IBinder onBind(Intent arg0) {
Log.i(TAG, "onBind()" );
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
public int onStartCommand(Intent intent, int flags, int startId) {
song_string= intent.getStringExtra("uri");
if (song_string != null) {
System.out.println("Song string : " + song_string);
player = MediaPlayer.create(this, Uri.parse(song_string));
player.setLooping(false); // Set looping
player.setVolume(0.5f, 0.5f);
if (!(String.valueOf(x) == null || String.valueOf(x).isEmpty())) {
player.seekTo(x);
}
player.start();
}
return Service.START_STICKY;
}
public IBinder onUnBind(Intent arg0) {
Log.i(TAG, "onUnBind()");
return null;
}
public void onStop() {
Log.i(TAG, "onStop()");
}
public void onPause() {
Log.i(TAG, "onPause()");
x=player.getCurrentPosition();
player.pause();
}
#Override
public void onDestroy() {
if(player!=null) {
player.stop();
player.reset();
player.release();
Log.i(TAG, "onCreate() , service stopped...");
}
}
#Override
public void onLowMemory() {
Log.i(TAG, "onLowMemory()");
}
}
Despite Sticky and declaration in Manifest , it still doesnt work in background. Also I want to add pause button and I dont know exacly how can I do that.

Related

Monitoring received SMS within a service

I'm trying to create a service that monitors received sms,
the service onStartCommand and OnCreate are getting called, however when I'm sending sms Broadcast receiver OnReceive is not getting called, What is the problem?
Here is my code:
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication"
tools:targetApi="31">
<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>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<service android:enabled="true" android:name="com.example.myapplication.SmsServices" />
<receiver android:name=".SmsListener"
android:exported="true" android:priority="1000">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
Service
public class SmsServices extends Service {
private SmsListener smslistener;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("SmsServices", "onStartCommand");
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
smslistener = new SmsListener();
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smslistener, filter);
Log.d("SmsServices", "Registered Sms Listener.");
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(smslistener);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Broadcast receiver
public class SmsListener extends BroadcastReceiver {
public SmsListener (){}
#Override
public void onReceive(Context context, Intent intent) {
Log.d("SmsListener", "Sms received.");
if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
String msgBody = smsMessage.getMessageBody();
String msgAddr = smsMessage.getOriginatingAddress();
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent( this, SmsServices.class ) );
Log.d("Main","Service Started.");
}
}

Android app in background

I have to create application and want to use it always when phone works, currently my code is:
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.plan.pedometer">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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:enabled="true"
android:name=".PedometerService"/>
<receiver
android:name=".receiver.StartPedometerServiceAtBootReceiver"
android:label="StartPedometerServiceAtBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
StartPedometerServiceAtBootReceiver:
public class StartPedometerServiceAtBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, PedometerService.class);
context.startService(serviceIntent);
}
}
}
Service:
public class PedometerService extends IntentService {
private int Steps=0;
public PedometerService() {
super("Pedometer_Worker_Thread");
}
#Override
protected void onHandleIntent(Intent intent) {
putInSharedPreferences();
synchronized (this) {
try {
wait(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void putInSharedPreferences(){
stepsNumbers = getApplicationContext().getSharedPreferences("stepsData", MODE_PRIVATE);
editorStepsNumbers=stepsNumbers.edit();
editorStepsNumbers.putInt(String.valueOf(STEPS),Steps).apply();
}
}
It works if I start Service in MainActivity by:
Intent intent = new Intent(getApplication(),PedometerService.class);
startService(intent);
and Service is running in background but when I restart my phone nothing happens and Service does not start.
I have one more question, this is Pedometer application, where should I put onSensorChange method in Service? Create something like while(1) in onHandleIntent() and put it there?
UPDATE - my actually code is:
I followed this tutorial https://github.com/codepath/android_guides/wiki/Starting-Background-Services
and tried to use WakefulBroadcastReceiver
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.plan.pedomoter">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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="com.plan.pedomoter.MyTestService"
android:exported="false"/>
<receiver android:name="com.plan.pedomoter.BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
launchTestService();
}
public void launchTestService() {
// Construct our Intent specifying the Service
Intent i = new Intent(this, MyTestService.class);
// Add extras to the bundle
i.putExtra("foo", "bar");
// Start the service
startService(i);
}
}
Receiver:
public class BootBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Launch the specified service when this message is received
Intent startServiceIntent = new Intent(context, MyTestService.class);
startWakefulService(context, startServiceIntent);
}
}
Service:
public class MyTestService extends IntentService {
Handler handler;
// Must create a default constructor
public MyTestService() {
// Used to name the worker thread, important only for debugging.
super("test-service");
}
#Override
public void onCreate() {
super.onCreate(); // if you override onCreate(), make sure to call super().
// If a Context object is needed, call getApplicationContext() here.
handler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
WakefulBroadcastReceiver.completeWakefulIntent(intent);
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyTestService.this, "start", Toast.LENGTH_LONG).show();
int i = 0;
}
});
int i=0;
while(true){
i++;
// Do some work here
if(i>1000)
i=0;
}
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(MyTestService.this, "stop", Toast.LENGTH_SHORT).show();
}
}
I used while(true) in MyTestService for check that app is running in background, in project I will use sensors (this is pedometer application) then I want to put something like MyAlarmReceiver from tutorial to send data to the server several times a day.
try this
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mkonuk.rebootapplication">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service android:name=".MyService"/>
<receiver android:name=".MyBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<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>
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(getBaseContext(),MyService.class));
}
}
MyService
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(),"Service started",Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(),"Service Destroyed",Toast.LENGTH_LONG).show();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
MyBootReceiver
public class MyBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context,MyService.class);
context.startService(service);
}
}
I have tested when application started service will be start , even if your application destroyed service will be started again.Even if reboot android device service will be started.
Second question :
if you will use sensor with service you need to register sensor listener and unregister sensor listener when service destroyed,oncreate method override sensor object and create sensor and sensor manager.In onstartCommand method register generated sensor listener sensor manager object ,unregister listener when service destroy
you can check this link
Accelemeter in android
if you want to send message from service to activity,you have to implement onbind() method ,activity need to bind on service check this link
bind activity on service using sensor
bind/unbind service
Hello I am a little new and looking for the some help, (It is not an answer) I coulndt add any other commentI was trying to execute a similar app, I followed what mithat show,then when I turn off my mobili it seems like it starts, but just when I put my cellphone password, it appears a system toast that says "app Stop", so i could t get it. Even when I sweep the app from 'Recent app" it says "app Stop"
I would like to run it for ever,
thanks

Android Wear not receiving OnDataChanged call

I have read any thread that is on this topic in the last 2 days.. but I still cannot figure out what is wrong with my code.
I have Mobile and Wear app. the mobile has only widget and widgetconfig activities (no main activity).
Here is the mobile app files:
AndroidManifest: (simple appwidget and appwidget_config activities)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.xx.yy.remotedoor">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/housek"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".DoorConf"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
<receiver android:name=".upDoor">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/up_door_info" />
</receiver>
</application>
</manifest>
upDoor.java: (Look at send_to_wear function)
package net.xx.yy.remotedoor;
import ...
public class upDoor extends AppWidgetProvider {
public static String TAG = "Remote door GAPI";
public static String CLICK_DOOR = "ClickDoorOpen";
public static String DOOR_ID = "DoorID";
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
CharSequence widgetText = "Test";
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.up_door_widget);
views.setTextViewText(R.id.textView, widgetText);
Intent intent = new Intent(context, upDoor.class);
intent.setAction(CLICK_DOOR);
intent.putExtra(DOOR_ID, Integer.toString(appWidgetId));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.houseIcon, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
send_to_wear(context);
}
}
private static void send_to_wear(Context context) {
// Sending data to wear
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected: " + connectionHint);
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d(TAG, "onConnectionFailed: " + result);
}
})
.addApi(Wearable.API)
.build();
Log.w("Google API", "Connecting");
mGoogleApiClient.connect();
Log.w("Google API", Boolean.toString(mGoogleApiClient.isConnected()));
PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/doors/1");
putDataMapReq.getDataMap().putString("caption", "test"); putDataMapReq.getDataMap().putLong("Time",System.currentTimeMillis());
putDataMapReq.setUrgent();
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
com.google.android.gms.common.api.ResultCallback<DataApi.DataItemResult> send_callback =
new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(#NonNull DataApi.DataItemResult result) {
if (!result.getStatus().isSuccess()) {
Log.w("Result", "Failed");
}else{
Log.w("Result", "Success");
}
Log.w("Item", result.getDataItem().getUri().toString());
Log.w("Reason", result.getStatus().getStatusMessage());
}
};
com.google.android.gms.common.api.PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
pendingResult.setResultCallback(send_callback);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
#Override
public void onEnabled(Context context) {...}
#Override
public void onDisabled(Context context) {...}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(CLICK_DOOR)) {
send_to_wear(context);
}
}
}
On the Wear side:
Manifest: (I configured it at same package name, is that ok?)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.xx.yy.remotedoor">
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="#drawable/housek"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#android:style/Theme.DeviceDefault">
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<activity
android:name=".main"
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=".dataLayer" android:exported="false" android:enabled="true">
<intent-filter>
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:scheme="wear" android:host="*" android:pathPrefix="*" />
</intent-filter>
</service>
</application>
</manifest>
and the dataLayer java part:
package net.xx.yy.remotedoor;
import ...
public class dataLayer extends WearableListenerService { //implements DataApi.DataListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LOG";
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.w(TAG, "Wear got on_change");
final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
// Do I need it??
ConnectionResult connectionResult = googleApiClient.blockingConnect(30, TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Log.e(TAG, "Failed to connect to GoogleApiClient.");
return;
}
for (DataEvent dataEvent : events) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
DataItem item = dataEvent.getDataItem();
Log.w(TAG, "item path: " + item.getUri().getPath());
if(item.getUri().getPath().startsWith("/doors/")){
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
// Do something
}
}
}
}
}
On the mobile log I can see:
DataItemResult : Success
Item: wear://HOST_ID/doors/1
On the wear log I cannot see anything related to this..
What am I doing wrong!?
Thanks!!

Try to resolve ActivityNotFoundException

I try to share a post on google+ but I obtain this Exception. The Activity that creates the Exception is ExampleActivity and this is its code:
public class ExampleActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = "ExampleActivity";
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
#Override//onCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
mPlusClient = new PlusClient.Builder(this, this, this)
.setVisibleActivities("http://schemas.google.com/AddActivity","http://schemas.google.com/BuyActivity")
.build();
// Progress bar to be displayed if the connection failure is not resolved.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
Button shareButton = (Button) findViewById(R.id.share_button);
shareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Launch the Google+ share dialog with attribution to your app.
Intent shareIntent = new PlusShare.Builder()
.setType("text/plain")
.setText("Welcome to
the Google+ platform.")
.setContentUrl(Uri.parse("https://developers.google.com/+/"))
.getIntent();
startActivityForResult(shareIntent, 0);
}
});
}
#Override//onStart
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
#Override//onStop
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override// onConnectionFailed
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the result and resolve the connection failure upon a user click.
mConnectionResult = result;
}
#Override //onActivityResult
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
// #Override
// public void onConnected(Bundle connectionHint) {
// String accountName = mPlusClient.getAccountName();
// Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
// }
#Override //onDisconnected
public void onDisconnected() {
String accountName = mPlusClient.getAccountName();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
}
#Override//onConnected
public void onConnected() {
// TODO Auto-generated method stub
}
#Override
public void onClick(View arg0) {
}
}
This is the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.applicazionescienza"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.applicazionescienza.Menu"
android:label="#string/app_name"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.applicazionescienza.Informazioni"
android:label="#string/title_activity_informazioni" >
</activity>
<activity
android:name="com.example.applicazionescienza.Regolamento"
android:label="#string/title_activity_regolamento" >
</activity>
<activity
android:name="com.example.applicazionescienza.Gioca"
android:label="#string/title_activity_gioca" >
</activity>
<activity
android:name="com.example.applicazionescienza.Livello"
android:label="#string/title_activity_livello" >
</activity>
<activity
android:name="com.example.applicazionescienza.Punteggio"
android:label="#string/title_activity_punteggio" >
</activity>
<activity
android:name="com.example.applicazionescienza.TwitterActivity"
android:label="#string/title_activity_twitter"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="casa"
android:scheme="app" />
</intent-filter>
</activity>
<activity
android:name="com.example.applicazionescienza.FacebookActivity"
android:label="#string/title_activity_facebook" >
</activity>
<activity
android:name="com.example.applicazionescienza.ExampleActivity"
android:label="#string/title_activity_example" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
The Exception say: No activity found to handle Intent(act=android.intent.action.SEND....
Someone can help me?
Try and clean the project, uninstall your app from device and reinstall.

Splash Screen will not display

I am trying to implement a Splash Screen using this java and xml code. I created a separate java class from my main activity and placed the java code inside. I created an xml layout in my layout file and placed the xml code inside. However, my app appears normally without a splash screen. It never shows, but the app does not have any errors. Eclipse is not showing any errors either. What could be the cause to this? Thank you in advance. Here is the code.
Java:
package com.carouseldemo.main;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
public class Splash extends Activity {
private final int SPLASH_DISPLAY_LENGHT = 1000;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.splash);
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(Splash.this,Menu.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="#+id/splashscreen" android:layout_width="wrap_content"
android:layout_height="fill_parent" android:src="#drawable/cat"
android:layout_gravity="center"/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Hello World, splash"/>
</LinearLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.carouseldemo.main"
android:versionCode="1"
android:versionName="1.0"
>
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" android:screenOrientation="portrait"/>
<application android:icon="#drawable/buttonone" android:label="#string/app_name">
<activity android:name=".MainActivity" android:label="#string/app_name" android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity is launcher activity in manifest file. So, splash is not showing.
Change the launcher activity MainActivity to Splash and write another for MainActivity.
<application android:icon="#drawable/buttonone" android:label="#string/app_name">
<activity android:name=".Splash" android:label="#string/app_name" android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" />
</application>
Replace the Handler part with this :
Thread splashThread = new Thread() {
public void run() {
try {
Thread.sleep(SPLASH_DISPLAY_LENGHT);
} catch (Exception e) {
} finally {
Intent i = new Intent(Splash.this,Menu.class);
startActivity(i);
finish();
}
}
};
splashThread.start();
private static final int STOPSPLASH = 0;
private static final long SPLASHTIME =3000;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
context = getApplicationContext();
if(savedInstanceState == null){
Message msg = new Message();
msg.what = STOPSPLASH;
spHandler.sendMessageDelayed(msg, SPLASHTIME);
}
}
private Handler spHandler = new Handler() {
#Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case STOPSPLASH:
gotoHomeScreen();
break;
default:
break;
}
super.handleMessage(msg);
}
};
public void gotoHomeScreen(){
Intent i = new Intent();
i.setClass(Splash.this,Home.class);
startActivity(i);
finish();
spHandler = null;
}
try this.
in your manifest
<activity android:name="Splash" android:configChanges="keyboardHidden" android:theme="#android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Try out as below :
public class Splash extends Activity
{
private final int SPLASH_DISPLAY_LENGHT = 1000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Thread(){
public void run()
{
try
{
sleep(SPLASH_DISPLAY_LENGHT);
Intent mainIntent = new Intent(Splash.this,Menu.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
};
}.start();
}
EDITED:
<activity android:name=".Splash" android:label="#string/app_name" android:screenOrientation="portrait" android:configChanges="orientation|keyboardHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Another way to achieve using CountDownTimer
public class MyCounter extends CountDownTimer {
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
startActivity(new Intent(SplashScreen.this,
TabSample.class));
finish();
MCObject.cancel();
}
#Override
public void onTick(long millisUntilFinished) {
}
}
Within OnCreate
MyCounter MCObject;
MCObject = new MyCounter(3000, 100);
MCObject.start();
Use this code, it might help you.
public class SplashScreenActivity extends Activity {
protected int _splashTime = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
Thread splashTread = new Thread() {
#Override
public void run() {
try {
sleep(_splashTime);
}
} catch (InterruptedException e) {
// do nothing
} finally {
startActivity(new Intent(SplashScreenActivity.this,
MainActivity.class));
SplashScreenActivity.this.finish();
}
}
};
splashTread.start();
}
Hope it will help you.
Replace your handler
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(SPLASH_TIME);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();

Categories