Lock Screen for android is not working properly using Android - android

for Lock Screen programmatically using Android. I got some good ideas from Stackoverflow previous questions regarding this, and I did some thing well, but when I run that code, there is No Exception and Error. but also , the screen didn't lock. kindly some one point my fault in this code
My manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.top"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".LockActivity">
</activity>
<activity
android:name=".LockActivity$Myclass"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".LockActivity"
android:label="device_admin"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin"
android:resource="#xml/my_admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
</manifest>
my Class file
package net.top;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.widget.Toast;
public class LockActivity extends DeviceAdminReceiver{
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}
#Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}
#Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}
void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
public static class Myclass extends Activity {
protected PowerManager.WakeLock mWakeLock;
DevicePolicyManager mDPM;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
// mDPM.lockNow();
ComponentName mAdminName = new ComponentName(Myclass.this,LockActivity.class);
if(!mDPM.isAdminActive(mAdminName))
{
Intent intent = new
Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
mAdminName);
//mDPM.lockNow();
}
else
{
mDPM.lockNow();
}
}
}
}
I also added the My_admin.xml file
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
<expire-password />
<encrypted-storage />
<disable-camera />
</uses-policies>
</device-admin>
I can't find what is goes wrong here. kindly help me to point out my mistake here. thanks in advance.

you can add this code into your Activity class, it's works fine for me
if(!mDPM.isAdminActive(mAdminName))
{
intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,"is locked");
intent.putExtra("force-locked", DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
startActivityForResult(intent, 1);
System.out.println("The Device Could not lock because device admin not enabled");
//mDPM.lockNow();
}
else
{
System.out.println("The Device device admin enabled");
intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,"onEnabled");
mDPM.lockNow();
mDPM.setMaximumTimeToLock(mAdminName, 0);
intent.putExtra("force-locked", DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
startActivityForResult(intent, 1);
}
Hope this would be helpful for you.

Related

Android BroadcastReciever BOOT_COMPLETED SecurityException

I search on internet 2 days but find nothing this is my
adb command
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
and``
this is my error code
Broadcasting: Intent { act=android.intent.action.BOOT_COMPLETED flg=0x400000 }
Security exception: Permission Denial: not allowed to send broadcast android.intent.action.BOOT_COMPLETED from pid=20913, uid=2000
java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.BOOT_COMPLETED from pid=20913, uid=2000
at com.android.server.am.ActivityManagerService.broadcastIntentLocked(ActivityManagerService.java:20474)
at com.android.server.am.HwActivityManagerService.broadcastIntentLocked(HwActivityManagerService.java:4226)
at com.android.server.am.ActivityManagerService.broadcastIntent(ActivityManagerService.java:21189)
at com.android.server.am.ActivityManagerShellCommand.runSendBroadcast(ActivityManagerShellCommand.java:614)
at com.android.server.am.ActivityManagerShellCommand.onCommand(ActivityManagerShellCommand.java:154)
at android.os.ShellCommand.exec(ShellCommand.java:96)
at com.android.server.am.ActivityManagerService.onShellCommand(ActivityManagerService.java:16149)
at android.os.Binder.shellCommand(Binder.java:574)
at android.os.Binder.onTransact(Binder.java:474)
at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:4285)
at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3286)
at com.android.server.am.HwActivityManagerService.onTransact(HwActivityManagerService.java:837)
at android.os.Binder.execTransact(Binder.java:675)
AND
THİS İS MY MANİFEST FİLE
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mir.kitapkurdu"
>
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="com.huawei.permission.external_app_settings.USE_COMPONENT"/>`
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<permission android:name="android.permission.NET_ADMIN"
android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
android:protectionLevel="signature">
</permission>
<application
android:installLocation="internalOnly"
android:name=".App"
android:persistent="true"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true">
<activity android:name=".Gonderici" />
<activity android:name=".Register" />
<activity android:name=".BookComplate" />
<activity android:name=".SpeechGame" />
<activity android:name=".BooksActvty" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Categories" />
<activity android:name=".PageComplete" />
<activity android:name=".Membership" />
<receiver
android:name=".SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="android.intent.action.REBOOT" />
<action android:name="android.permission.BOOT_COMPLETED" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED"/>
<action android:name="android.intent.action.ACTION_USER_PRESENT" />
<action android:name="com.mir.kitapkurdu.AN_INTENT" />
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="android.intent.action.ACTION_SHUTDOWN" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
<service android:name=".services.BootUpService"
android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>
</manifest>
Mainactvity.class
package com.mir.kitapkurdu;
import android.Manifest;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.speech.SpeechRecognizer;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import com.mir.kitapkurdu.objects.User;
import com.mir.kitapkurdu.services.BootUpService;
import com.mir.kitapkurdu.services.Database;
import com.mir.kitapkurdu.services.NotificaionService;
public class MainActivity extends AppCompatActivity {
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private String space = " ";
private Button ileri;
private TextView ekranayazdir;
private TextView startVoiceInput;
private Database db;
public BroadcastReceiver br = new SensorRestarterBroadcastReceiver();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db= new Database(MainActivity.this);
User user=new User();
user = db.getLastAddedUser();
if (user.user_name==null)
{
serviceControl();
/* BootUpService mBootUpService = new BootUpService();
Intent mServiceIntent = new Intent(getApplicationContext(), mBootUpService.getClass());
startService(mServiceIntent);*/
broadcastIntent();
Intent intent = new Intent(this, Membership.class);
// intent.putExtra("category_id", 59);
startActivity(intent);
finish();
}else{
serviceControl();
/* BootUpService mBootUpService = new BootUpService();
Intent mServiceIntent = new Intent(getApplicationContext(), mBootUpService.getClass());
startService(mServiceIntent);*/
broadcastIntent();
Intent intent = new Intent(this, Gonderici.class);
intent.putExtra("user_id", user.user_id);
startActivity(intent);
finish();
}
}
private void serviceControl(){
NotificaionService mSensorService = new NotificaionService(getApplicationContext());
Intent mServiceIntent = new Intent(getApplicationContext(), mSensorService.getClass());
if (!isMyServiceRunning(mSensorService.getClass())) {
startService(mServiceIntent);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("isMyServiceRunning?", true+"");
return true;
}
}
Log.i ("isMyServiceRunning?", false+"");
return false;
}
#Override
protected void onResume() {
super.onResume();
}
public void broadcastIntent() {
ComponentName receiver = new ComponentName(getPackageName(), "com.mir.kitapkurdu.SensorRestarterBroadcastReceiver");
PackageManager pm = MainActivity.this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Intent intent = new Intent();
intent.setComponent(receiver);
sendBroadcast(intent);
}
#Override
protected void onStop() {
super.onStop();
}
}
please help me I try everything on internet but There are no results I think this problem about permission what can I do in manifest file help me I want it this broadcast recieve to work at startup :(
The docs say:
This is a protected intent that can only be sent by the system.
https://developer.android.com/reference/android/content/Intent#ACTION_BOOT_COMPLETED
Which means that you cant send this intent.
You currently have <action android:name="android.permission.BOOT_COMPLETED" /> set as an intent filter, which won't work.
Add <action android:name="android.intent.action.BOOT_COMPLETED" /> to the intent filter of your SensorRestarterBroadcastReceiver, then reboot your device.

How to start an app at startup on Android?

I've tried:
This which doesn't work on my phone:
Trying to start a service on boot on Android
This which also fails to work properly:
http://www.compiletimeerror.com/2014/12/android-autostart-app-after-boot-with.html#.VpL6sxWLTIU
And a few others which I couldn't find again. Could someone please post a working example of code which will start a MainActivity with the default HelloWorld xml layout?
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name=".MyBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity
android:name=".MyService"
android:label="#string/title_activity_my_service" >
</activity>
</application>
</manifest>
package com.example;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, MyService.class);
context.startService(startServiceIntent);
}
}
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MyService extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_service);
}
}
First:create a BroadcastReceiver, onReceive(Context context, Intent intent),start the app you want to startup in this method
public class BootBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
xxx.class is the app you want to start
Intent service = new Intent(context,XXXclass);
context.startService(service);
Log.v("TAG", "you want to startup this app.....");
Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
context.startActivity(intent );
} }
Secondly:configure receiver and intent-filter
<receiver android:name="BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
THirdly,add permission
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

What kind of technology need I use if the function doWork will run a long time

The function doWork maybe run 20s, I think the system will cause ANR problem.
I don't know what kind of technology I need use to prevent ANR, AyncTask, local server, thread, IntentService or others.
Could you give me some sample codes? Thanks!
AlarmManagerBroadcastReceiver.java
package com.code4reference.enabledisablebroadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context context, Intent intent) {
doWork(context,intent);
}
private void doWork(Context context, Intent intent){
//It will running a long time.
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.enabledisablebroadcastreceiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.code4reference.enabledisablebroadcastreceiver.EnableDisableBroadcastReceiver"
android:label="#string/title_activity_enable_disable_boradcast_receiver" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Broadcast receiver -->
<receiver android:name="com.code4reference.enabledisablebroadcastreceiver.AlarmManagerBroadcastReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
</manifest>
EnableDisableBroadcastReceiver.java
package com.code4reference.enabledisablebroadcastreceiver;
import android.app.Activity;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.example.enabledisablebroadcastreceiver.R;
public class EnableDisableBroadcastReceiver extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnExit=(Button)findViewById(R.id.btnExit);
btnExit.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
public void enableBroadcastReceiver(View view){
ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();
}
public void disableBroadcastReceiver(View view){
ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();
}
}
activity_main.xml
<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">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="#dimen/padding_medium"
android:text="#string/enable_broadcast_receiver"
android:onClick="enableBroadcastReceiver"
tools:context=".EnableDisableBroadcastReceiver" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="#dimen/padding_medium"
android:text="#string/disable_broadcast_receiver"
android:onClick="disableBroadcastReceiver"
tools:context=".EnableDisableBroadcastReceiver" />
<Button
android:id="#+id/btnExit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Exit"
/>
</LinearLayout>

Android boot start app on boot from BroadcastReceiver with multiple services

I need to start 2 services on bootcompleted. The first service starts correctly, but second service seems is not starting.
I don't know if I have to create two BroadcastReceiver or it's enough with one.
Here is my code. I've put the two services in one BroadcastReceiver. Please, can you tell me what I'm doing wrong?
Thank you in advance
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pruebas.appservicelocator"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="internalOnly" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<!-- Startup service -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<!-- GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- UUID -->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<!-- Acceso a web service -->
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.pruebas.appservicelocator.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=".Servicio">
<intent-filter>
<action android:name="com.pruebas.appservicelocator.Servicio"/>
</intent-filter>
</service>
<service android:name=".ServicioBD">
<intent-filter>
<action android:name="com.pruebas.appservicelocator.ServicioBD"/>
</intent-filter>
</service>
<receiver android:name=".Recibidor" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
</application>
</manifest>
Recibidor.java:
package com.pruebas.appservicelocator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class Recibidor extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
android.os.Debug.waitForDebugger();
Toast.makeText(context, "Iniciando Recibidor", Toast.LENGTH_LONG).show();
final String TAG = "Recibidor";
Log.i(TAG, "Iniciando Recibidor");
if (intent.getAction().equalsIgnoreCase("android.intent.action.BOOT_COMPLETED")) {
Toast.makeText(context, "Iniciando Intent", Toast.LENGTH_LONG).show();
Log.i(TAG, "Iniciando Intent");
Intent servicio = new Intent();
servicio.setAction("com.pruebas.appservicelocator.Servicio");
context.startService(servicio);
Intent servicioBD = new Intent();
servicio.setAction("com.pruebas.appservicelocator.ServicioBD");
context.startService(servicioBD);
Log.i(TAG, "Iniciando Servicios");
Toast.makeText(context, "Iniciando Servicio", Toast.LENGTH_LONG).show();
}
}
}
"Servicio" service works fine, so I don't write the code. If you need, please, tell-me and I will write it.
ServicioBD.java:
package com.pruebas.appservicelocator;
import com.pruebas.utils.UsersLocationsDBHelper;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class ServicioBD extends Service{
private UsersLocationsDBHelper locDBHelper = null;
private static String TAG = "ServicioBD";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "SERVICIOBD ON CREATE", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(0, null);
Toast.makeText(this, "SERVICIOBD ON START COMMAND", Toast.LENGTH_LONG).show();
return START_STICKY;
}
}
I've found the error.
Intent servicio = new Intent();
servicio.setAction("com.pruebas.appservicelocator.Servicio");
context.startService(servicio);
Intent servicioBD = new Intent();
servicio.setAction("com.pruebas.appservicelocator.ServicioBD");
context.startService(servicioBD);
Has to be
Intent servicio = new Intent();
servicio.setAction("com.pruebas.appservicelocator.Servicio");
context.startService(servicio);
Intent servicioBD = new Intent();
servicioBD.setAction("com.pruebas.appservicelocator.ServicioBD");
context.startService(servicioBD);

Starting Activity from a non-Activity in c2dm not showing

I am trying to display messages from C2DM so When I start an Activity from a non activity it works but only first time. My activity contains View and close button so if the user is not inside the app when he receive the push notification then it should start the app when he press view button or close it on close this works as well but when user press view button and enters the app after than I am unable to start the activity again, it seems like the activity is there but its not visible to user. My code is as below , hope you understand what I am saying. The C2DM code example used is taken from here
C2DMReceiver
package com.mks.android.example;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.google.android.c2dm.C2DMBaseReceiver;
import com.google.android.c2dm.C2DMessaging;
import com.mks.android.example.activity.MessageDialogActivity;
public class C2DMReceiver extends C2DMBaseReceiver {
private static String senderId = "mysenderemail#gmail.com";
String registrationId;
public C2DMReceiver() {
super(senderId);
}
#Override
public void onRegistrered(Context context, String registrationId) {
this.registrationId = registrationId;
Log.e("Error", registrationId);
}
#Override
public void onUnregistered(Context context) {
C2DMessaging.register(context, senderId);
}
#Override
public void onError(Context context, String errorId) {
Log.w("Error", errorId);
}
#Override
protected void onMessage(Context context, Intent intent) {
Log.i("Error", "MessageReceived");
Bundle bundle = intent.getExtras();
intent = new Intent();
intent.putExtra("messageBundle", bundle);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
intent.setClass(context, MessageDialogActivity.class);
startActivity(intent);
// load message display activity here
}
}
MESSAGE DIALOG ACTIVITY CLASS
package com.mks.android.example.activity;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.mks.android.example.R;
import com.mks.android.example.activity.list.Functions;
public class MessageDialogActivity extends Activity {
private Functions func = new Functions();
private int isAppActive = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showMessages();
}
private void showMessages(){
Bundle bundle = getIntent().getBundleExtra("messageBundle");
String title = bundle.getString("title");
String message = bundle.getString("message");
setContentView(R.layout.c2dm_message);
TextView txtTitle = (TextView) findViewById(R.id.title);
TextView txtMessage = (TextView) findViewById(R.id.message);
Button btnView = (Button) findViewById(R.id.btnView);
Button btnClose = (Button) findViewById(R.id.btnClose);
txtTitle.setText(title);
txtMessage.setText(message);
this.isAppActive = func.getAppState(this);
if(isAppActive==1){
btnView.setVisibility(View.GONE);
}
btnView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(isAppActive == 0){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.mks.android.example","com.mks.android.example.activity.MainActivity"));
startActivity(intent);
}
MessageDialogActivity.this.finish();
}
});
btnClose.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
showMessages();
}
}
AndroidManifest FIle
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mks.android.example"
android:versionCode="1"
android:versionName="1.0" android:installLocation="preferExternal">
<uses-sdk android:minSdkVersion="4" />
<application android:label="#string/app_name" android:icon="#drawable/icon_launcher" android:debuggable="true">
<uses-library android:name="com.google.android.maps" />
<activity android:name=".activity.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
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>
<activity android:name=".activity.MessageDialogActivity" android:theme="#style/DialogNoTitle" android:activity android:launchMode="singleTop" />
<service android:name=".C2DMReceiver" />
<!-- Only C2DM servers can send messages for the app. If permission is not set - any other app can generate it -->
<receiver android:name="com.google.android.c2dm.C2DMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
<!-- Receive the actual message -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.mks.android.example" />
</intent-filter>
<!-- Receive the registration id -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.mks.android.example" />
</intent-filter>
</receiver>
</application>
<supports-screens android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true" />
<permission android:name="com.mks.android.example.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.mks.android.example.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive message -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
If i remove androidLaunchMode singleTop form manifest file and add set flag to multipleTask in C2DMReciver class it works but i get lots of dialog for each message. Thanks for help .
Set flag to singletop , the code to call messagedialogactivity is as under:
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setClass(context, MessageDialogActivity.class);

Categories

Resources