将我的手机设置为静音模式

时间:2014-01-26 16:13:59

标签: android class android-audiomanager

我有一个小部件,我正在尝试设置手机音量静音模式而不使用Activity

我的widget课程:

   public class MyWidget extends AppWidgetProvider {



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


    ComponentName thisWidget = new ComponentName(context,
        MyWidget.class);
    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
    for (int widgetId : allWidgetIds) {



      RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
          R.layout.widget_layout);

      Intent i = new Intent(context,mutee.class);
      PendingIntent i1 = PendingIntent.getActivity(context, 0, i, 0);
      remoteViews.setOnClickPendingIntent(R.id.imageButton4silent, i1);

    appWidgetManager.updateAppWidget(widgetId, remoteViews);
    }
  }
}

现在我想使用mutee class并设置我的手机音量silent 我实际上试过这个,但它不起作用:

public class mutee  {

    private Context context;    


     mutee(Context context){
        this.context=context;
    }

    private void setRingerMode (int ringerMode){

        AudioManager e = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        //ringerMode=0x00000002;//normal
        e.setRingerMode(ringerMode);


    }

     mutee() {
         setRingerMode(0x00000002);
    }

}

1 个答案:

答案 0 :(得分:1)

您可以将应用程序上下文保存在引用中,您可以轻松地将其传递给助手类。 在您的上下文中,您需要将该引用传递给您的Mute.class

代码片段用于保存应用程序参考文件: -

public class YourApplication extends Application{
  static YourApplication yourapplication;

  public void onCreate() {
            super.onCreate();
            yourapplication = this;
   }
   public static YourApplication getApplication()
    {
            return yourapplication;
    }
  public void onTerminate() {
            // TODO Auto-generated method stub
            super.onTerminate();
    }
}

现在yourapplication保留应用程序的上下文,

您可以在其上拨打getSystemService()

代码段: -

 AudioManager am;
 am= (AudioManager)yourapplication.getSystemService(Context.AUDIO_SERVICE);
 am.setRingerMode(AudioManager.RINGER_MODE_SILENT);

您需要从您的清单文件中调用YourApplication扩展应用程序

<application 
android:label="@string/app_name"
...
android:name="com.abc.demo.YourApplication"
...>