将Android音乐小部件用作LockScreen小部件

时间:2015-01-02 07:00:57

标签: android widget android-4.4-kitkat lockscreen

我正在拼命地在锁屏和桌面上显示我的音乐小部件。 但没有成功:(

我已经看了所有的SO和谷歌,教程和官方的Android文档和havnt发现为什么我的小部件没有在锁定屏幕上显示(At All)..

它有点简单的小部件,设计非常简单,所以我没有看到它没有显示的原因。

我正在尝试使用KitKat Os实现我的One Plus One。

这是代码(希望它也可以帮助其他用户创建他们的小部件):

Java代码:

public class MusicManager extends AppWidgetProvider {
boolean isLockScreen = false;
RemoteViews remoteViews;
Bundle options;

@Override
 public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

       Log.d("Widget Reciever", "Is Playing - " + Main.isPlaying);

    // Get all ids
    ComponentName thisWidget = new ComponentName(context,
            MusicManager.class);

    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
    for (int widgetId : allWidgetIds) {
         options = appWidgetManager.getAppWidgetOptions(widgetId);
         menageResorces(context);

        // Play Intent
        initPlayIntent(context, allWidgetIds, remoteViews, appWidgetManager, widgetId);        

        // Next Intent
        initNextIntent(context, allWidgetIds, remoteViews, appWidgetManager, widgetId);

        // Prev Intent
        initPrevIntent(context, allWidgetIds, remoteViews, appWidgetManager, widgetId);

        // Main Intent
        initMainIntent(context, allWidgetIds, remoteViews, appWidgetManager, widgetId);

        //Shuffle
        initShuffleIntent(context, appWidgetIds, remoteViews, appWidgetManager, widgetId);

        //Repeat
        initRepeatIntent(context, appWidgetIds, remoteViews, appWidgetManager, widgetId);

        //Bypass
        initBypassIntent(context, appWidgetIds, remoteViews, appWidgetManager, widgetId);
      }
 }

 private void initPlayIntent(Context context, int[] appWidgetIds, RemoteViews remoteViews,
         AppWidgetManager appWidgetManager, int widgetId){
        Intent playIntent = new Intent(context, MusicManager.class);
        playIntent.setAction(Constants.ACTION.PLAY_ACTION);
        playIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        PendingIntent pendingPlayIntent = PendingIntent.getBroadcast(context,
                0, playIntent, PendingIntent.FLAG_UPDATE_CURRENT);              
        remoteViews.setOnClickPendingIntent(R.id.btnPlay, pendingPlayIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);
 }

 private void initNextIntent(Context context, int[] appWidgetIds, RemoteViews remoteViews,
         AppWidgetManager appWidgetManager, int widgetId){
        Intent fastForwardIntent = new Intent(context, MusicManager.class);
        fastForwardIntent.setAction(Constants.ACTION.NEXT_ACTION);
        fastForwardIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        PendingIntent pendingNextIntent = PendingIntent.getBroadcast(context,
                0, fastForwardIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.btnNext, pendingNextIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);
 }

 private void initPrevIntent(Context context, int[] appWidgetIds, RemoteViews remoteViews,
         AppWidgetManager appWidgetManager, int widgetId){
        Intent fastBackwardIntent = new Intent(context, MusicManager.class);
        fastBackwardIntent.setAction(Constants.ACTION.PREV_ACTION);
        fastBackwardIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        PendingIntent pendingPrevIntent = PendingIntent.getBroadcast(context,
                0, fastBackwardIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.btnPrevious, pendingPrevIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);
 }

 private void initShuffleIntent(Context context, int[] appWidgetIds, RemoteViews remoteViews,
         AppWidgetManager appWidgetManager, int widgetId){
        Intent shuffleIntent = new Intent(context, MusicManager.class);
        shuffleIntent.setAction(Constants.ACTION.SHUFFLE);
        shuffleIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        PendingIntent pendingShuffleIntent = PendingIntent.getBroadcast(context,
                0, shuffleIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.btnShuffle, pendingShuffleIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);
 }

 private void initRepeatIntent(Context context, int[] appWidgetIds, RemoteViews remoteViews,
         AppWidgetManager appWidgetManager, int widgetId){
        Intent repeatIntent = new Intent(context, MusicManager.class);
        repeatIntent.setAction(Constants.ACTION.REPEAT);
        repeatIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        PendingIntent pendingRepeatIntent = PendingIntent.getBroadcast(context,
                0, repeatIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.btnRepeat, pendingRepeatIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);
 }

 private void initBypassIntent(Context context, int[] appWidgetIds, RemoteViews remoteViews,
         AppWidgetManager appWidgetManager, int widgetId){
        Intent bypassIntent = new Intent(context, MusicManager.class);
        bypassIntent.setAction(Constants.ACTION.BYPASS);
        bypassIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        PendingIntent pendingBypassIntent = PendingIntent.getBroadcast(context,
                0, bypassIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.bypass, pendingBypassIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);
 }

 private void initMainIntent(Context context, int[] appWidgetIds, RemoteViews remoteViews,
         AppWidgetManager appWidgetManager, int widgetId){
        Intent mainIntent = new Intent(context, MusicManager.class);
        mainIntent.setAction(Constants.ACTION.MAIN_ACTION);
        mainIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
        PendingIntent pendingMainIntent = PendingIntent.getBroadcast(context,
                0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.albumCover, pendingMainIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);
 }

 @Override
 public void onReceive(Context context, Intent intent) {
  // v1.5 fix that doesn't call onDelete Action
  final String action = intent.getAction();
  if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
       Log.d("Widget Reciever", "Widget DELETED");

   //The widget is being deleted off the desktop
   final int appWidgetId = intent.getExtras().getInt(
     AppWidgetManager.EXTRA_APPWIDGET_ID,
     AppWidgetManager.INVALID_APPWIDGET_ID);
   if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
       this.onDeleted(context, new int[] { appWidgetId });
   }
  } else {
      //Manage Play
      if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
          Log.d("Widget Reciever", "Widget Play");
          //If Main is running
          if(isRunning(context)){
              Log.d("Widget Reciever", "Activity Running");
              Main.btnPlay.performClick();

          }
          //If Main is NOT running
          else{
              startMainActivity(context);                 
          }
      //Manage Next
      } else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
           Log.d("Widget Reciever", "Widget Next");
          //If Main is running
          if(isRunning(context)){
              Main.btnNext.performClick();
          }
          //If Main is NOT running
          else{
              startMainActivity(context);
          }
      //Manage Previous
      } else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
           Log.d("Widget Reciever", "Widget Previous");
          //If Main is running
          if(isRunning(context)){
              Main.btnPrevious.performClick();
          }
          //If Main is NOT running
          else{
              startMainActivity(context);
          }
      //Manage Main
      } else if (intent.getAction().equals(Constants.ACTION.MAIN_ACTION)) {
           Log.d("Widget Reciever", "Widget Main");
          if(!isRunning(context)){
              startMainActivity(context);
          }
          else{
              moveToFront(context) ; 
          }
      //Manage Shuffle
      } else if (intent.getAction().equals(Constants.ACTION.SHUFFLE)) {
           Log.d("Widget Reciever", "Widget Shuffle");
          if(isRunning(context)){
              Main.btnShuffle.performClick();
          }
          else{

          }
      //Manage Repeat
      } else if (intent.getAction().equals(Constants.ACTION.REPEAT)) {
           Log.d("Widget Reciever", "Widget Repeat");
          if(isRunning(context)){
              Main.btnRepeat.performClick();
          }
          else{

          }
      //Manage Bypass
      } else if (intent.getAction().equals(Constants.ACTION.BYPASS)) {
           Log.d("Widget Reciever", "Widget Bypass");
          if(isRunning(context)){
              Main.bypass.performClick();
          }
          else{

          }
      }        
   super.onReceive(context, intent);
  }
 }

@SuppressLint("InlinedApi")
private void menageResorces(Context ctx){
         //Check if in lock screen or desktop
//       if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
//             try {
//                 int category = options.getInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY, -1);
//                 isLockScreen = category == AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD;
//                 Log.d("Widget Reciever", "Widget Can Be In Lock Screen");
//          } catch (NullPointerException e) {
//              isLockScreen = false;
//          } 
//      }
//      else{
//          isLockScreen = false;
//      }
//      if(isLockScreen == true){
//             Log.d("Widget Reciever", "Widget Is In Lock Screen");
//          remoteViews = new RemoteViews(ctx.getPackageName(),
//                  R.layout.lock_widget_layout);
//      }else{
        Log.d("Widget Reciever", "Widget Is NOT In Lock Screen");
        remoteViews = new RemoteViews(ctx.getPackageName(),
                R.layout.widget_layout);
//      }


    //Set album cover
    try {
        Bitmap icon;
        try {
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(Main.songBeingPlayedPath);
            byte [] data = mmr.getEmbeddedPicture();
            icon = BitmapFactory.decodeByteArray(data, 0, data.length);
            icon = scaleDownBitmap(icon, 100, ctx);
        } catch (NullPointerException e) {
            icon = BitmapFactory.decodeResource(ctx.getResources(),
                     R.drawable.list_image);
            icon = scaleDownBitmap(icon, 100, ctx);
        }catch (IllegalArgumentException e) {
            icon = BitmapFactory.decodeResource(ctx.getResources(),
                     R.drawable.list_image);
            icon = scaleDownBitmap(icon, 100, ctx);
        }

        try {           
            remoteViews.setImageViewBitmap(R.id.albumCover, icon);
        } catch (IllegalArgumentException e) {
            try {
                icon = BitmapFactory.decodeResource(ctx.getResources(),
                         R.drawable.list_image);
                icon = scaleDownBitmap(icon, 100, ctx);
                remoteViews.setImageViewBitmap(R.id.albumCover, icon);
            } catch (IllegalArgumentException e1) {
                e1.printStackTrace();
            }
        }
    } catch (NullPointerException e) {
    }       

    //Set play button image
    try {   
        //Set Song Label
        if(Main.songBeingPlayedTitle != null && Main.songBeingPlayedTitle.length() > 0){
            remoteViews.setTextViewText(R.id.songName, Main.songBeingPlayedTitle);

            try {
                if(Main.cameFromPlayerButtonWithShuffle == true)
                    remoteViews.setTextViewText(R.id.album_name, Main.songListShuffle.get(Main.currentSongIndex).getAlbum());
                else
                    remoteViews.setTextViewText(R.id.album_name, Main.songListAdapter.getItem(Main.currentSongIndex).getAlbum());
            } catch (NullPointerException e) {
            }
        }
        //Set Un Active
        else{
            remoteViews.setTextViewText(R.id.songName, ctx.getString(R.string.player_not_active));
            remoteViews.setTextViewText(R.id.album_name,"");
        }
        if(Main.isPlaying == true){
            Log.d("Widget Reciever", "Set Pause Button");
            remoteViews.setImageViewResource(R.id.btnPlay, R.drawable.btn_pause);           
        }
        else{
            Log.d("Widget Reciever", "Set Play Button");
            remoteViews.setImageViewResource(R.id.btnPlay, R.drawable.btn_play);            
        }
        if(Main.isRepeat == true){
            Log.d("Widget Reciever", "Set Repeat On");
            remoteViews.setImageViewResource(R.id.btnRepeat, R.drawable.btn_repeat_focused);            
        }
        else{
            Log.d("Widget Reciever", "Set Repeat Off");
            remoteViews.setImageViewResource(R.id.btnRepeat, R.drawable.btn_repeat);            
        }
        if(Main.isShuffle == true){
            Log.d("Widget Reciever", "Set Shuffle On");
            remoteViews.setImageViewResource(R.id.btnShuffle, R.drawable.btn_shuffle_focused);          
        }
        else{
            Log.d("Widget Reciever", "Set Shuffle Off");
            remoteViews.setImageViewResource(R.id.btnShuffle, R.drawable.btn_shuffle);          
        }
        if(Main.bypassed == true){
            Log.d("Widget Reciever", "Set Bypass On");
            remoteViews.setTextViewText(R.id.bypass, ctx.getString(R.string.bypass_440));           
        }
        else{
            Log.d("Widget Reciever", "Set Bypass Off");
            remoteViews.setTextViewText(R.id.bypass, ctx.getString(R.string.bypass_432));           
        }

    } catch (NullPointerException e) {
    }

 } 

 private void startMainActivity(Context ctx){
   Intent mainIntentStart = new Intent (ctx, Main.class);
   mainIntentStart.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
   ctx.startActivity (mainIntentStart);
 }

 //Is Activity Running
 public boolean isRunning(Context ctx) {
    ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

    for (RunningTaskInfo task : tasks) {
        if (ctx.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName())) 
            return true;                                  
    }

    return false;
 }  

 //Move Activity To Front
protected void moveToFront(Context context) {
    final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    final List<RunningTaskInfo> recentTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

    for (int i = 0; i < recentTasks.size(); i++) 
    {
           // bring to front                
           if (recentTasks.get(i).baseActivity.toShortString().indexOf("com.appums.music_pitcher") > -1) {                     
              activityManager.moveTaskToFront(recentTasks.get(i).id, ActivityManager.MOVE_TASK_WITH_HOME);

           }
    }
}

public static Bitmap scaleDownBitmap(Bitmap photo, int newHeight, Context context) {

     final float densityMultiplier = context.getResources().getDisplayMetrics().density;        

     int h= (int) (newHeight*densityMultiplier);
     int w= (int) (h * photo.getWidth()/((double) photo.getHeight()));

     photo=Bitmap.createScaledBitmap(photo, w, h, true);

     return photo;
 }

窗口小部件提供程序Xml:

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/widget_layout"
android:previewImage="@drawable/widget_preview"
android:minWidth="216dp"
android:minHeight="72dp"
android:initialKeyguardLayout="@layout/widget_layout"
android:resizeMode="horizontal|vertical"
android:widgetCategory="home_screen|keyguard"
android:updatePeriodMillis="10000" >

小工具布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/player_footer_bg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/purple" >

<LinearLayout
    android:id="@+id/song_name_ll"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="4dip" >

    <ImageView
        android:id="@+id/albumCover"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="4dp"
        android:layout_weight="1"
        android:src="@drawable/list_image" />

    <LinearLayout
        android:id="@+id/songDetails_ll"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/songName"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="3"
            android:gravity="center"
            android:text="@string/player_not_active"
            android:textColor="@android:color/background_light"
            android:textSize="@dimen/sub_text_size" />

        <TextView
            android:id="@+id/album_name"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1.1"
            android:gravity="center"
            android:textColor="@color/back_main"
            android:textSize="@dimen/indicator_text_small" />
    </LinearLayout>
</LinearLayout>

<LinearLayout
    android:id="@+id/btns"
    android:layout_width="match_parent"
    android:layout_height="@dimen/alert_button_height"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/song_name_ll"
    android:background="@android:color/background_dark"
    android:orientation="horizontal" >

    <ImageButton
        android:id="@+id/btnRepeat"
        android:layout_width="0dp"
        android:layout_height="@dimen/alert_button_height"
        android:layout_margin="@dimen/nav_drawer_header_divider_height"
        android:layout_weight="1"
        android:background="@null"
        android:padding="@dimen/row_marging"
        android:scaleType="fitCenter"
        android:src="@drawable/btn_repeat" />

    <ImageView
        android:id="@+id/btnPrevious"
        android:layout_width="0dp"
        android:layout_height="@dimen/alert_button_height"
        android:layout_margin="@dimen/nav_drawer_header_divider_height"
        android:layout_weight="1"
        android:background="@null"
        android:scaleType="fitCenter"
        android:src="@drawable/btn_previous" />

    <ImageView
        android:id="@+id/btnPlay"
        android:layout_width="0dp"
        android:layout_height="@dimen/alert_button_height"
        android:layout_margin="@dimen/nav_drawer_header_divider_height"
        android:layout_weight="1"
        android:background="@null"
        android:scaleType="fitCenter"
        android:src="@drawable/btn_play" />

    <ImageView
        android:id="@+id/btnNext"
        android:layout_width="0dp"
        android:layout_height="@dimen/alert_button_height"
        android:layout_margin="@dimen/nav_drawer_header_divider_height"
        android:layout_weight="1"
        android:background="@null"
        android:scaleType="fitCenter"
        android:src="@drawable/btn_next" />

    <ImageView
        android:id="@+id/btnShuffle"
        android:layout_width="0dp"
        android:layout_height="@dimen/alert_button_height"
        android:layout_margin="@dimen/nav_drawer_header_divider_height"
        android:layout_weight="1"
        android:background="@null"
        android:padding="@dimen/row_marging"
        android:scaleType="fitCenter"
        android:src="@drawable/btn_shuffle" />

    <TextView
        android:id="@+id/bypass"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:text="@string/bypass_432"
        android:textColor="@android:color/background_light"
        android:textSize="@dimen/indicator_text_small" />
</LinearLayout>

正如我所提到的,代码和小部件本身运行完美! 它根本不会在锁屏上显示。

0 个答案:

没有答案