Android Device Policy Manager not working - java

I'm trying to make a simple app that'll lock the screen of the device when an incoming call is accepted. For this, I'm made a custom device admin with the help of this tutorial. But, when I click the "Enable" button in my app, the Device Policy Manager activity does not open at all! And I get output in the logcat window that says that my ComponentName is invalid. However, I do not find any problems in my project what so ever!
MainActivity.java
package com.swap.delay;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
DevicePolicyManager devicePolicyManager;
ActivityManager activityManager;
ComponentName componentName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
componentName = new ComponentName(this, LockAdmin.class);
}
public void OnClickActivate(View view) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Lock Admin by Swap");
startActivityForResult(intent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
Toast.makeText(getBaseContext(), "Lock Admin by Swap added successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
LockAdmin.java
package com.swap.delay;
import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;
public class LockAdmin extends DeviceAdminReceiver{
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
#Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Lock Admin Enabled");
}
#Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Lock Admin: Wrong Password");
}
#Override
public void onPasswordSucceeded(Context context, Intent intent) {
//showToast(context, "Sample Device Admin: pw succeeded");
}
}
policies.xml
<device-admin xmlns:android="http://schemas.android.com/apk/res/auto">
<uses-policies>
<force-lock>
</force-lock>
</uses-policies>
</device-admin>
Receiver(Added to manifest.xml)
<receiver android:name=".LockAdmin" android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin" android:resource="#xml/policies">
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED">
</action></intent-filter>
</meta-data></receiver>
Logcat output -
08-25 12:52:40.103 652-1906/? I/ActivityManager﹕ START u0 {act=android.app.action.ADD_DEVICE_ADMIN cmp=com.android.settings/.DeviceAdminAdd (has extras)} from uid 10172 on display 0
08-25 12:52:40.162 652-1070/? I/ActivityManager﹕ Start proc com.android.settings for activity com.android.settings/.DeviceAdminAdd: pid=6313 uid=1000 gids={41000, 9997, 3002, 3001, 3003, 1028, 1015, 1000, 1021, 3004, 3005, 3009, 1023, 1010, 1007} abi=arm64-v8a
08-25 12:52:40.332 6313-6313/? W/DeviceAdminAdd﹕ Request to add invalid device admin: ComponentInfo{com.swap.delay/com.swap.delay.LockAdmin}
P.s. - I tested out the app on two different devices on based on AOSP KitKat(4.4.2) and another one CyanogenOS 12.0(5.0.2), it didn't work on either of them.

Related

Daily Notification in Android not working

I wanted my Application to send notification everyday to the user, following this link and doing everything as described. The app doesn't send notifications. The buildLocalNotification function is being triggered every 60 seconds, but no Notification is displayed. I kept an Interval of 2000 ms but android changed it to 60 Seconds.
Logcat Message: Suspiciously short interval 2000 millis; expanding to 60 seconds Every 60 seconds the notification function is triggered.
This is my
NotfBroadcastReceiver.class
import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import androidx.core.app.NotificationCompat;
#SuppressWarnings("deprecation")
public class NotfBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Get notification manager to manage/send notifications
//Intent to invoke app when click on notification.
//In this sample, we want to start/launch this sample app when user clicks on notification
Intent intentToRepeat = new Intent(context, SplashScreen.class);
//set flag to restart/relaunch the app
intentToRepeat.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Pending intent to handle launch of Activity in intent above
PendingIntent pendingIntent =
PendingIntent.getActivity(context, NotificationHelper.ALARM_TYPE_ELAPSED, intentToRepeat, PendingIntent.FLAG_UPDATE_CURRENT);
//Build notification
Notification repeatedNotification = buildLocalNotification(context, pendingIntent).build();
//Send local notification
NotificationHelper.getNotificationManager(context).notify(NotificationHelper.ALARM_TYPE_ELAPSED, repeatedNotification);
}
public NotificationCompat.Builder buildLocalNotification(Context context, PendingIntent pendingIntent) {
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(android.R.drawable.arrow_up_float)
.setContentTitle("Workout Reminder")
.setAutoCancel(true);
Log.d("DEBUG", "buildLocalNotification: "+"Notification");
return builder;
}
This is my
AlarmBootReceiver.class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
//only enabling one type of notifications for demo purposes
NotificationHelper.scheduleRepeatingElapsedNotification(context);
}
}
}
This is the code that turn notification on and off:
swnotf.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b)
{
if(b)
{
Log.d("DEBUG", "onCheckedChanged: "+ "ON");
CommonFunctions.setSwitchState(getContext(),"ON");
NotificationHelper.scheduleRepeatingElapsedNotification(getContext());
NotificationHelper.enableBootReceiver(getContext());
}
else
{
Log.d("DEBUG", "onCheckedChanged: "+"OFF");
CommonFunctions.setSwitchState(getContext(),"OFF");
NotificationHelper.cancelAlarmElapsed();
NotificationHelper.disableBootReceiver(getContext());
}
}
});
Please I have already spent THREE days trying other solutions and fixing this. I don't want to spend more time on this. Any help would be Appreciated.
Thank you.

Simple Media Player in Android

I am trying to create a media player without MediaPlayer class, just a very basic VideoView which selects a file from device and plays it. But I am receiving an error
Can't play this video.
Here's my code:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.VideoView;
public class PlayerActivity extends AppCompatActivity {
VideoView videoPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoPlayer = findViewById(R.id.videoView);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 7);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
String PathHolder = data.getData().getPath();
Toast.makeText(this, PathHolder, Toast.LENGTH_SHORT).show();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
videoPlayer.setVideoURI(Uri.parse(PathHolder));
videoPlayer.requestFocus();
videoPlayer.start();
}
}
}
}
XML file:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent">
<VideoView
android:id="#+id/videoView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="318dp"
tools:layout_editor_absoluteY="716dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is what logcat shows (i guess this contains the error):
2020-08-09 12:55:37.585 21894-21894/com.phantom.player W/MediaPlayer:
Couldn't open /document/primary:WhatsApp/Media/WhatsApp
Video/VID-20191031-WA0041.mp4
java.io.FileNotFoundException: No content provider: /document/primary:WhatsApp/Media/WhatsApp
Video/VID-20191031-WA0041.mp4
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1680)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1510)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1427)
at android.media.MediaPlayer.attemptDataSource(MediaPlayer.java:1149)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1121)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1145)
at android.widget.VideoView.openVideo(VideoView.java:412)
at android.widget.VideoView.access$2200(VideoView.java:83)
at android.widget.VideoView$7.surfaceCreated(VideoView.java:694)
at android.view.SurfaceView.updateSurface(SurfaceView.java:926)
at android.view.SurfaceView.windowStopped(SurfaceView.java:315)
at android.view.ViewRootImpl.setWindowStopped(ViewRootImpl.java:1973)
at android.view.WindowManagerGlobal.setStoppedState(WindowManagerGlobal.java:709)
at android.app.Activity.performRestart(Activity.java:8039)
at android.app.ActivityThread.handleSleeping(ActivityThread.java:5007)
at android.app.ActivityThread.access$2500(ActivityThread.java:268)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2080)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7807)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)
I am not used to content provider.Please help.
I didn't understand what was the problem.But it was solved when I changed onActivityResult to
switch (requestCode) {
case 7:
if (resultCode == RESULT_OK) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
videoPlayer.setVideoURI(data.getData());
videoPlayer.requestFocus();
videoPlayer.start();
}
}
Try to set orientation with object of video player
case 7:
if (resultCode == RESULT_OK) {
String PathHolder = data.getData().getPath();
Toast.makeText(this, PathHolder, Toast.LENGTH_SHORT).show();
videoPlayer.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
videoPlayer.setVideoURI(Uri.parse(PathHolder));
videoPlayer.requestFocus();
videoPlayer.start();
}

Multiple notifications with different data

I have an issue with my app that i cant solve. The app takes the input(reminder) from a user and then sets it as a notification. The user can create as many notifications as he/she likes. I want the user to click the notification and get taken to a new activity(Reminder), so he/she can see the reminder in a TextView. So i have an activity(SetReminder), which let the user put his data in a text editor.Then i save his data in a hashMap. The int is the id of user's string data. Then i have a class (AlarmReceiver) which extends BroacastReceiver and generates the notification.In this class i have an id for each notification,which matches the hashMap's int from the SetReminder activity. That way i was expecting that the user would see the data of each notification.But that's doesn't happen. I have multiple Notifications(i want that), but the user sees the data of the last notification, no matter which notifications selects. I am posting the code from the three activities.
Thanks in advance.
SetReminder.class
package demo.push_not_demo;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.widget.EditText;
import com.kunzisoft.switchdatetime.SwitchDateTimeDialogFragment;
import java.util.HashMap;
public class SetReminder extends AppCompatActivity {
private SwitchDateTimeDialogFragment dateTimeFragment;
Button b1,b2,b3;
EditText editText;
public static int counter=0;
public static HashMap<Integer,String> hashMap;
private static final String TAG_DATETIME_FRAGMENT = "TAG_DATETIME_FRAGMENT";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_reminder);
hashMap= new HashMap<Integer, String>();
b1=(Button) findViewById(R.id.set_date_time);
b2=(Button) findViewById(R.id.cancel);
b3=(Button) findViewById(R.id.save);
b1.setOnTouchListener(touch);
b2.setOnTouchListener(touch);
b3.setOnTouchListener(touch);
editText=(EditText) findViewById(R.id.reminder_edit);
}
View.OnTouchListener touch= new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()){
case R.id.set_date_time:
if (event.getAction()==MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
}
else if (event.getAction()== MotionEvent.ACTION_UP){
v.getBackground().clearColorFilter();
v.invalidate();
// Construct SwitchDateTimePicker
dateTimeFragment = (SwitchDateTimeDialogFragment) getSupportFragmentManager().findFragmentByTag(TAG_DATETIME_FRAGMENT);
if(dateTimeFragment == null) {
dateTimeFragment = SwitchDateTimeDialogFragment.newInstance(
getString(R.string.label_datetime_dialog),
getString(R.string.positive_button_datetime_picker),
getString(R.string.negative_button_datetime_picker)
);
}
dateTimeFragment.show(getSupportFragmentManager(), TAG_DATETIME_FRAGMENT);
}
break;
case R.id.cancel:
if (event.getAction()==MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
cancelalarm();
}
else if (event.getAction()== MotionEvent.ACTION_UP){
v.getBackground().clearColorFilter();
v.invalidate();
Intent intent = new Intent(SetReminder.this,HomeScreen.class);
startActivity(intent);
}
break;
case R.id.save:
if (event.getAction()==MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
}
else if (event.getAction()== MotionEvent.ACTION_UP){
v.getBackground().clearColorFilter();
v.invalidate();
counter++;
hashMap.put(counter,editText.getText().toString());
alarmservice();
}
break;
}
return false;
}
};
public void alarmservice(){
Intent intent = new Intent(this,AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(alarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime()+ 5000,pendingIntent);
}
public void cancelalarm(){
Intent intent = new Intent(this,AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}
AlertReceiver.class
package demo.push_not_demo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.widget.EditText;
import java.util.HashMap;
import static android.support.v4.app.NotificationCompat.DEFAULT_SOUND;
import static android.support.v4.app.NotificationCompat.PRIORITY_HIGH;
import static android.support.v4.app.NotificationCompat.VISIBILITY_PUBLIC;
public class AlertReceiver extends BroadcastReceiver {
public static int id=0;
#Override
public void onReceive(Context context, Intent intent) {
id++;
createNotification(context);
}
private void createNotification(Context context) {
NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setSmallIcon(R.drawable.offer1)
.setContentTitle("Notification Title")
.setContentText("Tap to see your reminder")
.setPriority(PRIORITY_HIGH)
.setVibrate(new long[] { 50, 1000, 500, 1000, 1000 })
.setDefaults(DEFAULT_SOUND)
.setVisibility(VISIBILITY_PUBLIC);
Intent intent = new Intent(context,Reminder.class);
PendingIntent pendingintent = PendingIntent.getActivity(context,id,intent,PendingIntent.FLAG_ONE_SHOT);
notification.setContentIntent(pendingintent);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification ntfc = notification.build();
nm.notify(id,ntfc);
}
}
Reminder.class
package demo.push_not_demo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import static demo.push_not_demo.AlertReceiver.id;
import static demo.push_not_demo.SetReminder.hashMap;
public class Reminder extends AppCompatActivity{
TextView txtv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reminder);
txtv=(TextView) findViewById(R.id.reminder_textView);
txtv.setText(hashMap.get(id));
}
}
dont use static id,in your code id is always 0. you can check it using Log!
use another way for produce different ids.
when you add notification with same id, the new notification will replace with last notification. use random integer for id

Android no Activity Found to Handle Intent MediaScanner

im trying to open a Gallery with Images/Videos from a specific Folder. I´m using this solution but im getting the error code below and nothing happens. I guess its something abot the Uri but i cant find a solution. Has anyone an Idea how to solve this? I also included "my" code.
03-15 16:30:53.733 21902-22775/de.comidos.fotoapp D/onScanCompleted: Scan completed: content://media/external/images/media/1730
03-15 16:30:53.752 21902-22775/de.comidos.fotoapp D/Instrumentation: checkStartActivityResult() : Intent { act=android.intent.action.VIEW dat=content://media/external/images/media/1730 launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 } }
03-15 16:30:53.773 21902-22775/de.comidos.fotoapp W/Binder: Binder call failed.
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=content://media/external/images/media/1730 launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 } }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1839)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1531)
at android.app.Activity.startActivityForResult(Activity.java:4389)
at android.app.Activity.startActivityForResult(Activity.java:4348)
at android.app.Activity.startActivity(Activity.java:4672)
at android.app.Activity.startActivity(Activity.java:4640)
at de.comidos.fotoapp.GalleryViewActivity.onScanCompleted(GalleryViewActivity.java:59)
at android.media.MediaScannerConnection$1.scanCompleted(MediaScannerConnection.java:55)
at android.media.IMediaScannerListener$Stub.onTransact(IMediaScannerListener.java:60)
at android.os.Binder.execTransact(Binder.java:573)
package de.comidos.fotoapp;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import java.io.File;
public class GalleryViewActivity extends Activity implements MediaScannerConnection.MediaScannerConnectionClient {
public String[] allFiles;
private String SCAN_PATH ;
private static final String FILE_TYPE = "*/*";
private MediaScannerConnection conn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
File folder = new File(Environment.getExternalStorageDirectory().toString()+"/comidos/sent/");
allFiles = folder.list();
// uriAllFiles= new Uri[allFiles.length];
for(int i=0;i<allFiles.length;i++)
{
Log.d("all file path"+i, allFiles[i]+allFiles.length);
}
// Uri uri= Uri.fromFile(new File(Environment.getExternalStorageDirectory().toString()+"/yourfoldername/"+allFiles[0]));
SCAN_PATH= Environment.getExternalStorageDirectory().toString()+"/comidos/sent/"+allFiles[0];
Log.d("SCAN PATH", "Scan Path " + SCAN_PATH);
}
private void startScan()
{
Log.d("Connected","success"+conn);
if(conn!=null)
{
conn.disconnect();
}
conn = new MediaScannerConnection(this,this);
conn.connect();
}
#Override
public void onMediaScannerConnected() {
Log.d("onMediaScannerConnected","success"+conn);
conn.scanFile(SCAN_PATH, FILE_TYPE);
}
#Override
public void onScanCompleted(String path, Uri uri) {
try {
Log.d("onScanCompleted","Scan completed: "+uri );
if (uri != null)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} finally
{
conn.disconnect();
conn = null;
}
}
#Override
public void onResume(){
super.onResume();
startScan();
}
}
There is no activity on your device that supports ACTION_VIEW of a content Uri for whatever MIME type that content is. There is no requirement for an Android device to have an ACTION_VIEW activity for every possible piece of content.

Logical Flow of all Intents (PendingIntents) in this app widget snippet

I am learning how to build home screen widget in Android. This code is for an app widget to toggle RingerMode from NORMAL to SILENT and vice-versa.
This works fine but I need a full in-sight of logical flow (i.e which gets initiated when, goes where, does what, dies when) of all the intents in this.
Please help me understand this topic clearer.
package com.dummies.android.silentmodetoggle;
import android.app.Activity;
import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;
import android.widget.RemoteViews;
public class AppWidget extends AppWidgetProvider {
public static String tag ="SilentModeToggleWidget";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d(tag, "onReceive() first line");
if(intent.getAction()==null)
{
//Do Something
Log.d(tag, "before startService()");
context.startService(new Intent(context, ToggleService.class));
}
else{
super.onReceive(context, intent);
}
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// Do something in specified intervals
context.startService(new Intent(context, ToggleService.class));
}
public static class ToggleService extends IntentService{
public ToggleService(){
super("AppWidget$ToggleService");
Log.d(tag, "In ToggleService construcor");
}
#Override
protected void onHandleIntent(Intent arg0) {
Log.d(tag, "In ToggleService > onHandleIntent");
// TODO Auto-generated method stub
ComponentName cn = new ComponentName(this, AppWidget.class);
AppWidgetManager mgr = AppWidgetManager.getInstance(this);
mgr.updateAppWidget(cn, buildUpdate(this));
}
private RemoteViews buildUpdate(Context context){
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget);
AudioManager audioManager = (AudioManager)context.getSystemService(Activity.AUDIO_SERVICE);
if(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT){
updateViews.setImageViewResource(R.id.phoneState, R.drawable.phone_on);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
else{
updateViews.setImageViewResource(R.id.phoneState, R.drawable.phone_silent);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
Intent i = new Intent(this, AppWidget.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
updateViews.setOnClickPendingIntent(R.id.phoneState, pi);
return updateViews;
}
}
}
still not sure on what are u asking, but I'll try to answer, if not what u want, please explain in a different way.
Intent are usually started immediatly. You create an Intent can start it by calling startService or startActivity, so for example:
context.startService(new Intent(context, ToggleService.class));
on both times you wrote the above code, the service ToggleService is immediatly started.
PendingIntent on the other hand are saved to be started at later time, so for example
updateViews.setOnClickPendingIntent(R.id.phoneState, pi);
on the above line, the AppWidget Broadcast is started when the user clicks on R.id.phoneState in your HomeScreen AppWidget.
Each PendingIntent is stored in the system with a certain ID, this ID is the requestCode parameter (you used zero on your code)... that means, that if you create a different PendingIntent with the same ID it will override it, meaning a different action will be started when the user clicks on R.id.phoneState

Categories